[DDC-2922] Flushing new Entities reachable over several paths that do not all "cascade persist" Created: 17/Jan/14  Updated: 18/Aug/14

Status: Awaiting Feedback
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.



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

Can this be factored into a failing test case? I'm not sure if we can support it, but the code would make it much easier to track down the issue into something fixable.





[DDC-2838] Leaky abstraction when applying Criteria to hydrated/non-hydrated PersistentCollection Created: 03/Dec/13  Updated: 26/Jun/15

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

Type: Bug Priority: Major
Reporter: brian ridley Assignee: Marco Pivetta
Resolution: Unresolved Votes: 2
Labels: None

Attachments: File DDC2838Test.php    
Issue Links:
Reference
is referenced by DCOM-275 Collections\Expr\ClosureExpressionVis... Open
is referenced by DCOM-249 Criteria are unable to locate getters... Open

 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



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

We can't check out an entire project just to test a bug.

Please write an actual functional test case that can be integrated into the Doctrine ORM test suite.

Comment by brian ridley [ 20/Aug/14 ]

Hi,

i'm happy to do so - i'll take a look at this over the weekend.

Comment by Simon Paridon [ 12/Dec/14 ]

brian ridley: Any progress on this? This is currently an issue for us as well and hope to get fixed. I could look into converting it to a test for integration with the test suite if you don't have the time... but it might take a while since I have no experience with the requirements that should be met. (Plus, I am not sure how tightly coupled it is with your project)

Comment by Simon Paridon [ 17/Dec/14 ]

Hi Marco Pivetta, brian ridley,

I attached a functional Test that integrates with the test suite. Please let me know if I should issue a PR, and I'll do that this evening.

Comment by Florian Preusner [ 26/Dec/14 ]

+1

Comment by Simon Paridon [ 26/Jun/15 ]

My idea to solve this would go like this:

  • Add a new class ObjectCollection in Common that implements Collection and Selectable, but requires class metadata.
  • Whenever creating an ArrayCollection with entities / other objects, create an ObjectCollection instead.

The only thing that's causing me a headache is that ideally, there should be code sharing in some form between the matching() implementations of ObjectCollection and PersistentCollection, because both will use class metadata. Maybe this can be achieved somehow using a trait?

If you like the idea, I could look into it further.





[DDC-2424] Removing an inherited entity via a delete cascade constraint does not remove the parent row Created: 02/May/13  Updated: 15/Oct/14

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

Type: Bug Priority: Major
Reporter: Bruno Jacquet Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 3
Labels: inheritance, postgresql
Environment:

Mysql 5.1.66 / Symfony 2.2.1



 Description   

For a parent class:

/**
 * @ORM\Entity
 * @ORM\Table(name="Base")
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @ORM\DiscriminatorMap({"child1" = "Child1", "child2" = "Child2"})
 */

and simple Child1 & Child2 entities.

With another entity (let's call it ExternalEntity) having a bidirectional OneToOne relation owned by Child1:

class Child1 extends Base
{
  /**
   * @ORM\OneToOne(targetEntity="ExternalEntity", inversedBy="xxx")
   * @ORM\JoinColumn(onDelete="CASCADE", nullable=false)
   */
   private theForeignKey;
}

Enough for the context.
The symptoms:

$em->remove(instanceOfExternalEntity);

removes the ExternalEntity row and the Child1 row. But a dangling row in the Base table is still there for the now inexistent Child1 instance.

Though, a manual delete of either the associated Child1 OR Base row and then the ExternalEntity works.

The problem with the cascading deletion of the parent seems to be only present when deleting through a MYSQL cascading delete from another row which has a foreign key on a child. (Not tested with a foreign key on the parent though)



 Comments   
Comment by Benjamin Eberlei [ 04/May/13 ]

Can you show the CREATE TABLE and FOREIGN KEY statements of all the tables involved? It seems the cascade of the foreign keys is not propagated between multiple tables?

Comment by Bruno Jacquet [ 06/May/13 ]

CREATE TABLE Base (id INT AUTO_INCREMENT NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
CREATE TABLE Child1 (id INT NOT NULL, foreignKey INT NOT NULL, UNIQUE INDEX UNIQ_179B6E88E992F5A (foreignKey), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;

ALTER TABLE Child1 ADD CONSTRAINT FK_179B6E88E992F5A FOREIGN KEY (foreignKey) REFERENCES ExternalEntity (id) ON DELETE CASCADE;
ALTER TABLE Child1 ADD CONSTRAINT FK_179B6E8BF396750 FOREIGN KEY (id) REFERENCES Base (id) ON DELETE CASCADE;

Comment by Bruno Jacquet [ 06/May/13 ]

The problem is that, the SQL model never explicitely tells the DB to delete the corresponding Base when Child1 gets removed. It looks like it is handled by the doctrine entity manager layer and not the actual DB engine (Base has no on delete cascade nor foreign key to its children).
So only doctrine can add the logic here because it knows the entity schema. But in this case, when it is deleted from another table, it looks like the special treatment is not triggered.

Comment by Bruno Jacquet [ 06/May/13 ]

Maybe using

cascade={"remove"}

, instead of

onDelete="CASCADE"

to force the cascading process to be handled by doctrine would workaround the bug... But I prefer to have my DB do the logic work as much as possible.

Comment by J [ 25/Apr/14 ]

I've got a similar problem but I have InheritanceType("SINGLE_TABLE") instead of JOINED.
Any updates on when this is getting fixed?





[DDC-1988] Add Any and ManyToAny annotations Created: 18/Aug/12  Updated: 10/Jul/14

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

Type: New Feature Priority: Minor
Reporter: Stefano Rodriguez Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: None


 Description   

It would be really nice to have @Any and @ManyToAny relations/annotations implemented like on Hibernate.
http://docs.jboss.org/hibernate/orm/4.1/javadocs/org/hibernate/annotations/ManyToAny.html
Right now I've implemented these in a Symfony2 bundle (that I'd be happy to share once it's ready and a bit documented), using listeners on postLoad, preFlush and prePersist
However I think this is a very common use case that anyone will encounter at least once/twice in every middle/big-sized project, and for this reason I think this should be implemented as a core feature.






[DDC-3287] PreUpdateEventArgs need to extend Doctrine\Common\PreUpdateEventArgs Created: 29/Aug/14  Updated: 15/Jan/15

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

Type: Improvement Priority: Trivial
Reporter: Sebastian Kuhlmann Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: inheritance, orm

Issue Links:
Reference
relates to DDC-3320 [GH-1144] [DDC-3287] Change parent cl... Resolved

 Description   

Currently the inheritance tree of the EventArgs don't allow for creating event listeners that fit both ORM- and MongoDB-driven applications.

Doctrine\Common defines base classes for Lifecycle event arguments. Doctrine\ORM uses the common library and extends it's classes. So does MongoDB. If you wanted to write something that suits both ORM and MongoDB you should be able to rely on the Common-implementations.

The provided classes to extend:

  • Doctrine\Common\Persistence\Event\LifecycleEventArgs
  • Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs
  • Doctrine\Common\Persistence\Event\ManagerEventArgs
  • Doctrine\Common\Persistence\Event\OnClearEventArgs
  • Doctrine\Common\Persistence\Event\PreUpdateEventArgs

Checking the Github repository there is no common ground for the inheritance mechanism.

  • Doctrine\ORM\Event\LifecycleEventArgs extends Doctrine\Common\Persistence\Event\LifecycleEventArgs
  • Doctrine\ORM\Event\PreUpdateEventArgs extends Doctrine\ORM\Event\LifecycleEventArgs
  • Doctrine\ORM\Event\PreFlushEventArgs extends Doctrine\Common\EventArgs
  • Doctrine\ORM\Event\PostFlushEventArgs extends Doctrine\Common\EventArgs
  • Doctrine\ORM\Event\OnFlushEventArgs extends Doctrine\Common\EventArgs
  • Doctrine\ORM\Event\OnClearEventArgs extends Doctrine\Common\EventArgs

This needs to change and ORM\PreUpdateEventArgs as well as ORM\OnClearEventArgs need to extend the respective events from Doctrine\Common.



 Comments   
Comment by Sebastian Kuhlmann [ 23/Sep/14 ]

See https://github.com/doctrine/doctrine2/pull/1144

Comment by Christophe Coevoet [ 04/Oct/14 ]

All flush event args should be updated to extend ManagerEventArgs (and marking their getEntityManager method as deprecated too)

Comment by Christophe Coevoet [ 04/Oct/14 ]

to be clear, the change on PreUpdateEventArgs cannot be done until 3.0 because of BC

Comment by Doctrine Bot [ 19/Oct/14 ]

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

Comment by Doctrine Bot [ 15/Jan/15 ]

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





[DDC-2285] Repeating the same query with different parameter value returns the same results Created: 08/Feb/13  Updated: 08/Feb/13  Resolved: 08/Feb/13

Status: Closed
Project: Doctrine 2 - ORM
Component/s: DQL, Mapping Drivers, ORM
Affects Version/s: 2.3.2
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: Mehdi Bakhtiari Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: None
Environment:

Ubuntu 12.10, Zend Server CE



 Description   
$activeAdsCustomers = \Ez\Registry::getDoctrineEntityManager()
    ->createQuery( "SELECT c, a FROM \Spot101\Model\Ad\Customer c JOIN c.ads a WHERE a.status = :status" )
    ->setParameter( "status", \Spot101\Model\Ad\Status::ACTIVE )
    ->getResult();

$inactiveAdsCustomers = \Ez\Registry::getDoctrineEntityManager()
    ->createQuery( "SELECT c, a FROM \Spot101\Model\Ad\Customer c JOIN c.ads a WHERE a.status = :status" )
    ->setParameter( "status", \Spot101\Model\Ad\Status::INACTIVE )
    ->getResult();

Having the code above I am getting the same results for $inactiveAdsCustomers as I get for $activeAdsCustomers. And when I try hydrating the results everything works so fine.

Both queries look the same except the value provided for the "status" parameter.



 Comments   
Comment by Marco Pivetta [ 08/Feb/13 ]

You are hydrating joined and filtered resultsets. You should never do this, as this will hydrate an invalid association into your objects.





[DDC-2036] indexBy breaks cascade remove Created: 20/Sep/12  Updated: 03/Oct/12  Resolved: 03/Oct/12

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

Type: Bug Priority: Critical
Reporter: James Bench Assignee: Fabio B. Silva
Resolution: Can't Fix Votes: 0
Labels: None
Environment:

Ubuntu 12.04, PHP 5.3, 64 Bit, Symfony 2


Attachments: File AbstractData.php     File DDC2036Test.php     File Location.php     File LocationData.php     Text File msql.log     Text File sql_flush.log    

 Description   

Adding the annotation indexBy causes the cascade annotation to be ignored:

/**
*

  • @var ArrayCollection
  • @ORM\OneToMany(targetEntity="LocationData", mappedBy="location", indexBy="name", cascade= {"persist", "remove"}

    )
    */
    protected $data;

Will cause an error when deleting the objects:

An exception occurred while executing 'DELETE FROM location WHERE id = ?' with params

{"1":19306}

:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`symfony`.`location_data`, CONSTRAINT `FK_2DF7462364D218E` FOREIGN KEY (`location_id`) REFERENCES `location` (`id`))

Removing indexBy fixes the issue.

My class structure is:

Location has many LocationData
LocationData extends AbstractData

The name field I am trying to index by comes from the AbstractData class.



 Comments   
Comment by Fabio B. Silva [ 23/Sep/12 ]

Hi James

Do you have a failing test case ?
Could you attach/paste your entity please ?

Thanks

Comment by James Bench [ 28/Sep/12 ]

Entity exhibiting the behavior.

Comment by Fabio B. Silva [ 29/Sep/12 ]

Hi James,
I can't reproduce,

Are you sure that you dont have more than one LocationData whith the same name ?

When working with indexBy the index columns must be unique into the collection.
I recommend that you add a unique constrain in the columns name.

If i'm wrong about it, please
Could you change the added test case and try to make it fails ?

Thanks

Comment by James Bench [ 02/Oct/12 ]

Hi Fabio,

The test case uses a SQLite DB without any foreign keys so the issue wouldn't be apparent.

How would I run the test against a MySQL db?

I've also attached the SQL log for the script I'm running, it looks the same as the output from the testcase.

Cheers,JB

Comment by James Bench [ 02/Oct/12 ]

SQL Log from script causing errors.

Comment by Fabio B. Silva [ 02/Oct/12 ]

Hi James,

You must copy phpunit.xml.dist to phpunit.xml and change the database configurations.

I have attached the mysql log, the test case works fine.

Comment by James Bench [ 02/Oct/12 ]

It appears that it only attempts to delete 68 LocationData rows but in the database there are 76.

Comment by James Bench [ 02/Oct/12 ]

Okay, I've found the reason for this; the name isn't unique, some are duplicated.
Once the duplicates are removed there are 68 rows.
I'll add a unique index to the name column and hopefully this problem will go away.

Not sure whether you would consider this a bug.

Thanks for your help.

Comment by Fabio B. Silva [ 02/Oct/12 ]

No problem, you are welcome

Actually isn't a bug, it is a documented behavior.

"Fields that are used for the index by feature HAVE to be unique in the database."

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/working-with-indexed-associations.html#working-with-indexed-assocations

Comment by Fabio B. Silva [ 03/Oct/12 ]

Fields that are used for the index by feature HAVE to be unique in the database.

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/working-with-indexed-associations.html#working-with-indexed-assocations





[DDC-2404] Filter using join tables Created: 19/Apr/13  Updated: 12/Sep/13  Resolved: 11/Sep/13

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

Type: New Feature Priority: Major
Reporter: Filip Procházka Assignee: Benjamin Eberlei
Resolution: Won't Fix Votes: 1
Labels: filter, filters, join, joins


 Description   

Allow filters to add join tables to sql queries for filtering.

Let's have Brand entity, and BrandText entity. Text is localisation for each Brand. If there is no BrandText with bt.isPublic and bt.web_id = 123 I wanna filter it globally and not even allow to load Brand entity.

This cannot be solved by using DQL, because I need to affect lazily loaded associations, for example in templates

Accessing $product->brand-> in template should resolve to NULL, when there is no BrandText.isPublic = 1.

This could be solved by allowing filters to add joins to queries. Should I prepare a pull request?



 Comments   
Comment by Oleg Namaka [ 21/Apr/13 ]

Duplicates http://www.doctrine-project.org/jira/browse/DDC-2220

Comment by Filip Procházka [ 21/Apr/13 ]

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

Comment by Filip Procházka [ 11/Sep/13 ]

Because the DDC-2220 is closed.

Comment by Benjamin Eberlei [ 11/Sep/13 ]

We won't add this feature.

Comment by Filip Procházka [ 11/Sep/13 ]

I don't understand it... Think about it once again, you've never used inner joins, or left joins with where is null for filtering results?

Comment by Filip Procházka [ 11/Sep/13 ]

And I don't what the ugly api that is mentioned in DDC-2220, I wanna addFilterJoin method here, next to addFilterConstraint https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Query/Filter/SQLFilter.php#L128

Ok then, you're not going to support this, let's assume you have good reasons for it. What are the alternatives? If you give me working filtering alternative based on WHERE statements what won't kill the server performance I'm going to give up on this issue.

Comment by Filip Procházka [ 11/Sep/13 ]

Have there at least been some discussion somewhere I can read it? So I can understand why you don't like this? The "We won't add this feature." isn't a reason.

// Btw, jira could really use some comment edits...

Comment by Benjamin Eberlei [ 12/Sep/13 ]

Filip Procházka You can use a subselect, but we cannot extend the filters to add joins for technical reasons. An implementation would raise the complexity for all the code, not just the one affected by filters.

You could try to return a JOIN from 'addFilterConstraint', but I am not sure if that works (and i would recommend it)





[DDC-2399] unserializing returns proxyclass name with slashes Created: 12/Apr/13  Updated: 12/Apr/13  Resolved: 12/Apr/13

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

Type: Bug Priority: Major
Reporter: Quintenvk Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: None
Environment:

OSX, PHP 5.4.9



 Description   

I serialize a "user"-entity using the following code:

$user->getBusinessid()->getId(); //this is necessary to load the proxy
$em->detach($user);
$_SESSION['user'] = serialize($user);

When I unserialize said entity with this code:

$em = self::getEntityManager();
$user = unserialize($_SESSION['user']);
return $em->merge($user);

I get an error like this:
require(): Failed opening required './core/project/Proxy/_CG_/core/project/Entity/Businesses.php' .

The thing is that everything after _CG_ should not have any forward slashes. In that case the path would be completely correct.



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

There's an appositely coded autoloader in the ORM in 2.3 ( https://github.com/doctrine/doctrine2/blob/2.3.3/lib/Doctrine/ORM/Proxy/Autoloader.php ) and in common in 2.4-RC ( https://github.com/doctrine/common/blob/2.4.0-RC1/lib/Doctrine/Common/Proxy/Autoloader.php ). Proxies are not PSR-0 compliant

Comment by Quintenvk [ 12/Apr/13 ]

Ah, I hadn't found anything about that. Thank you!





[DDC-2378] Efficient count using Selectable Created: 28/Mar/13  Updated: 16/May/14  Resolved: 28/Mar/13

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

Type: Improvement Priority: Major
Reporter: Michaël Gallego Assignee: Marco Pivetta
Resolution: Duplicate Votes: 0
Labels: criteria, selectable


 Description   

Hi,

I'm currently using intensively the Criteria and Selectable interfaces to provide a generic REST library.

However, I've found a problem when I want to paginate data:

count
return count($this->selectable->matching(new Criteria()));

The problem is that EntityRepository returns an ArrayCollection and, hence, load the whole collection which is inefficient. It would be nice if it could return a PersistentCollection instead with lazy-load and perform an optimized count.

Thanks



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

duplicate of DDC-2217

Comment by Doctrine Bot [ 16/May/14 ]

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





[DDC-2358] [GH-621] [doc] adding some more doc and examples for lifecycle event listeners and subscribers Created: 19/Mar/13  Updated: 14/Oct/14  Resolved: 06/Apr/13

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

Type: Documentation Priority: Major
Reporter: Benjamin Eberlei Assignee: Guilherme Blanco
Resolution: Fixed Votes: 0
Labels: None


 Description   

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

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

Message:

as requested in https://github.com/symfony/symfony-docs/pull/2301



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

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





[DDC-2317] [UnitOfWork] Entity in identityMap but not present in entityIdentifiers Created: 24/Feb/13  Updated: 26/Feb/13  Resolved: 26/Feb/13

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

Type: Bug Priority: Major
Reporter: Rémi Piotaix Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: orm, unitofwork
Environment:

php 5.4.11, MySQL 5.5, ubuntu 12.10


Attachments: File Buff.php     File Competence.php     File CompetenceAction.php     File CompetenceActionBuff.php     File CompetenceActionBuffType.php    

 Description   

I'm using symfony 2.1.8 and sonata/admin-bundle
I have a quite complex entity mapping.

  • A Competence has many CompetenceAction (superclass)
  • CompetenceActionBuff is a subclass of CompetenceAction and has exactly one buff (selectable in the form by an 'entity' field).

When i want to edit a Competence, i have the following error message about the Buff entity linked to the CompetenceActionBuff:
"Entities passed to the choice field must be managed. [...]"
The exception is raised in Symfony/Bridge/Doctrine/Form/ChoiceList/EntityChoiceList.php at line 412

I've added some debug code in the EntityManager::contains() method and it shows that my entity is in the entityMap but his oid is not in the keys of entityIdentifiers making the call to UnitOfWork::isInIdentityMap() return false at line 1505.

When submitting the form, there is no problems. All the entities are correctly created in the database. The exception is thrown only when i want to edit the Competence object. Saying that the Buff object is not managed when it was first loaded from the database... strange, no?

Finally, i tried to comment the test

if (!$this->em->contains($entity)))

in EntityChoiceList::getIdentifierValues() and everything seemed to work properly.



 Comments   
Comment by Marco Pivetta [ 24/Feb/13 ]

Can you please reproduce this in an insulated environment (without symfony forms involved)?

Comment by Rémi Piotaix [ 24/Feb/13 ]

By doing this, all work properly, the exception is not thrown:

$competence = $this->getRepo(\Sistearth\JeuBundle\Entity\Competence\Competence::REPO)->find(1);
$buff = $competence->getActions()[0]->getBuff();
      
$em = $this->getDoctrine()->getEntityManager();
        
if(!$em->contains($buff))
    throw new \Exception("Not in EntityManager");

but if i add this after:

$form = $this->createForm(new \Sistearth\JeuBundle\Form\Competence\CompetenceType(), $competence);

then, the exception "Entities passed to the choice field must be managed. Maybe persist them in the entity manager?" is back.

I'll try to do some others tests...

Comment by Marco Pivetta [ 24/Feb/13 ]

Rémi Piotaix the problem is exactly the last bit Doctrine has no forms, so you will have to create a small script that reproduces the problem without symfony, starting from:

php composer.phar require doctrine/orm:dev-master@dev
Comment by Rémi Piotaix [ 24/Feb/13 ]

Bug found!

In the form type CompetenceActionBuffType, i marked the field buff with

array('by_reference"=>false)

. If by_reference is set to false, the modelData is cloned (here the Buff proxy) at line 349 in Form.php.
And, by cloning the object, the spl_object_hash of the clone is different from the original one's.

Is this a symfony Form component bug or a doctrine one?

Comment by Marco Pivetta [ 26/Feb/13 ]

Rémi Piotaix this is a problem of symfony forms, please report it on the symfony issue tracker (check if there's a similar open issue first) at https://github.com/symfony/symfony/issues/





[DDC-2244] One-To-Many Cascade saving not working properly Created: 15/Jan/13  Updated: 15/Jan/13  Resolved: 15/Jan/13

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

Type: Bug Priority: Major
Reporter: Paweł Łaskarzewski Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: None


 Description   

I have the following code:

$new = new InterviewReview();

$question = new InterviewReviewQuestion();
$new->addQuestion($question);

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

When i execute this code i have the following error:

An exception occurred while executing 'INSERT INTO interview_review_question (question, tags, created_at, interview_review_id) VALUES (?, ?, ?, ?)' with params {"1":"asdfg","2":"asdfg","3":null,"4":null}:

Column 'interview_review_id' cannot be null

Here are my entities:

/**
 * InterviewReview
 *
 * @ORM\Table(name="interview_review")
 * @ORM\Entity
 */
class InterviewReview
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var Doctrine\Common\Collections\ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="Absolvent\AbsolventBundle\Entity\InterviewReviewQuestion", cascade={"persist", "remove"}, mappedBy="interview_review")
     * @ORM\JoinColumn(name="interview_review", referencedColumnName="id")
     */
    private $questions;

    /**
     * Add question
     *
     * @param \Absolvent\AbsolventBundle\Entity\InterviewReviewQuestion $question
     * @return InterviewReview
     */
    public function addQuestion(\Absolvent\AbsolventBundle\Entity\InterviewReviewQuestion $question)
    {
        $this->questions[] = $question;

        return $this;
    }

    /**
     * Remove question
     *
     * @param \Absolvent\AbsolventBundle\Entity\InterviewReviewQuestion $question
     */
    public function removeQuestion(\Absolvent\AbsolventBundle\Entity\InterviewReviewQuestion $question)
    {
        $this->questions->removeElement($question);
    }

    /**
     * Get questions
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getQuestions()
    {
        return $this->questions;
    }
}


/**
 * InterviewReviewQuestion
 *
 * @ORM\Table(name="interview_review_question")
 * @ORM\Entity
 */
class InterviewReviewQuestion
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var Absolvent\AbsolventBundle\Entity\InterviewReview
     *
     * @ORM\ManyToOne(targetEntity="Absolvent\AbsolventBundle\Entity\InterviewReview", cascade={"persist", "remove"}, inversedBy="questions")
     * @ORM\JoinColumn(name="interview_review_id", referencedColumnName="id", nullable=false)
     */
    private $interview_review;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set interview_review
     *
     * @param \Absolvent\AbsolventBundle\Entity\InterviewReview $interviewReview
     * @return InterviewReviewQuestion
     */
    public function setInterviewReview(\Absolvent\AbsolventBundle\Entity\InterviewReview $interviewReview = null)
    {
        $this->interview_review = $interviewReview;

        return $this;
    }

    /**
     * Get interview_review
     *
     * @return \Absolvent\AbsolventBundle\Entity\InterviewReview
     */
    public function getInterviewReview()
    {
        return $this->interview_review;
    }
}

This problem is causing because the is no $question->setInterviewReview() called anywhere.

I know that i can call it inside addQuestion function, but is should work out of the box - isn't it?



 Comments   
Comment by Marco Pivetta [ 15/Jan/13 ]

Fixing code highlighting

Comment by Paweł Łaskarzewski [ 15/Jan/13 ]

Fixed

Comment by Marco Pivetta [ 15/Jan/13 ]

Works here with your code. What's the exact ORM version you're using?

Comment by Marco Pivetta [ 15/Jan/13 ]

Calling

$question->setInterviewReview($this);

is up to you. Doctrine does not apply this kind of "magic".
You are responsible for keeping your object graph consistent.

Comment by Paweł Łaskarzewski [ 15/Jan/13 ]

In composer (using symofny) i have:

"doctrine/orm": ">=2.2,<2.4-dev"

and got the latest version.

Lanuched composer update 2 hours ago

Comment by Paweł Łaskarzewski [ 15/Jan/13 ]

Ok but both objects are new and connected (using add function). I thought that cascade=

{"persist"}

will do this magic

Comment by Marco Pivetta [ 15/Jan/13 ]

No, associating them is up to you. The ORM is only responsible for saving/loading data, not for manipulating your associations like that.

Comment by Paweł Łaskarzewski [ 15/Jan/13 ]

In the documentation there is some info about this:

http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/working-with-associations.html#transitive-persistence-cascade-operations

Even if you persist a new User that contains our new Comment this code would fail if you removed the call to EntityManager#persist($myFirstComment). Doctrine 2 does not cascade the persist operation to all nested entities that are new as well.
[....]
To have Doctrine handle both cases automatically we can change the User#commentsAuthored property to cascade both the “persist” and the “remove” operation.

Comment by Marco Pivetta [ 15/Jan/13 ]

Paweł Łaskarzewski see DDC-2227

Comment by Paweł Łaskarzewski [ 15/Jan/13 ]

Ok thanks for your help





[DDC-2177] WHERE IN not working Created: 28/Nov/12  Updated: 29/Nov/12  Resolved: 28/Nov/12

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

Type: Bug Priority: Major
Reporter: Moritz Kraft Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None
Environment:

Linux, Symfony 2, PHP 5.3.10



 Description   

I'm going by the docs, trying to get a WHERE IN type of query working with the query builder.

I've got a flat array of IDs, e.g. something like this:

$IDs = array( 228052, 265635, 344498, 391761, 329203, 317911, 305961, 299939, 249429, 344706 );

I've tried the following ways to get this working:

  • using the Expr class:

$qb->add( 'where', $qb->expr()->in( 'c.id', ':IDs' ));
$qb->setParameter( 'IDs', $IDs );

  • alternatively:

$qb->add( 'where', $qb->expr()->in( 'c.id', $IDs ));

  • even direct DQL:

$qb->where( 'c.id IN (:IDs)' );
$qb->setParameter( 'IDs', $IDs );

The generated DQL looks fine:

SELECT c FROM MyEntity c WHERE c.id IN('228052', '265635', '344498', '391761', '329203', '317911', '305961', '299939', '249429', '344706')

But when I call execute() on that query, all these variations give me the following error:

Expected argument of type "Doctrine\ORM\QueryBuilder", "array" given



 Comments   
Comment by Moritz Kraft [ 28/Nov/12 ]

never mind.... it was something i was doing wrong. thank god...

Comment by Marco Pivetta [ 28/Nov/12 ]

Moritz Kraft what was it exactly?

Comment by Moritz Kraft [ 29/Nov/12 ]

The error was thrown by the Symfony Form Framework, not Doctrine. Sorry about that. :-/





[DDC-1628] onUpdate parameter on @JoinColumn not supported Created: 31/Jan/12  Updated: 30/Jul/15  Resolved: 21/Mar/13

Status: Closed
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers
Affects Version/s: 2.2
Fix Version/s: None

Type: Task Priority: Major
Reporter: Chris Richard Assignee: Marco Pivetta
Resolution: Invalid Votes: 3
Labels: None


 Description   

It looks like this is in the older documentation (2.0) but not mentioned in the latest.

I need to use ON UPDATE CASCADE in a few cases. Seems odd to support onDelete and not onUpdate. Am I missing something?



 Comments   
Comment by Benjamin Eberlei [ 31/Jan/12 ]

We removed onUpdate because we couldnt come up with a use-case. CAn you share yours?

Comment by Chris Richard [ 08/Mar/12 ]

I assume it's just the mysql driver but all the constraints get created such that you cannot change the primary keys (even if it's not an auto-gen PK). ON UPDATE CASCADE would probably be a better default.

Comment by Kaspars Sproģis [ 28/Aug/12 ]

I really hope onUpdate annotation attribute will be restored.
I used it in PostgreSQL very often. In some entities in some projects Primary Key ID can be very important its sequence, and if you want to change it, then "ON UPDATE CASCADE" changed it for all the references too. It was must have feature. Now few of my applications are broken with latest doctrine orm.
Please consider restoring it back.
Thank you

Comment by Václav Novotný [ 11/Oct/12 ]

+1 - onUpdate attribute is very useful for PostgreSQL databases, it controls operations with foreign keys.

Comment by Kenneth Kataiwa [ 10/Nov/12 ]

What do you mean, you couldn't come up with a use-case? If one is migrating data from one table to another and requires that all foreign key references be changed to map the ones in the new table created, before deleting the last table. And there are may more case. Maybe I am missing some thing here, if it's a use-case for the MySQL and PostgreSQL guys, why would you not support it.

Comment by Marco Pivetta [ 10/Nov/12 ]

Kenneth Kataiwa updating identifiers is something you don't do, and I sincerely also don't have a use case for this, not in the context of an ORM at least. Also, handling changes in your identifiers in the UnitOfWork is a real problem that adds a lot overhead.

Comment by Václav Novotný [ 12/Nov/12 ]

+1 - onUpdate attribute is very useful for PostgreSQL databases, it controls operations with foreign keys.

I'm taking my words back. It is not a good idea to define onUpdate on foreign keys. Yes, PostgreSQL supports it but it doesn't mean that we should use it in ORM.
Thanks for your time.

Comment by Marco Pivetta [ 21/Mar/13 ]

This issue is invalid, since data migration is not a task for the ORM anyway.

Comment by Gary Golden [ 01/May/13 ]

I have a third party table which holds users:

CREATE TABLE `user`
(
`user_id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`email` VARCHAR(255) NOT NULL UNIQUE,
) ENGINE=InnoDB CHARSET="utf8";

In my table I want to use natural foreign key, so I reference `email`.

CREATE TABLE `transaction` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`user_email` VARCHAR(255) NOT NULL,
FOREIGN KEY (`user_email`) REFERENCES `user`(`email`)
);

I would like to RDBMS handle email updates on the foreign records.

That is a real-life use case of the onDelete, which you decided to remove.
Please, get it back if possible.

Comment by I. S. [ 07/Jan/14 ]

I have a good use case and I am really missing the onUpdate cascade.
However it is working inside a many-to-one association but not in a one-to-one association.
The use case is a little complicated but I can send it to you if it could change something.

Comment by James Hudson [ 30/Jul/15 ]

Sorry to drag this up again, but…

I've also come across a use case as I'm migrating data in MySQL. I had to migrate data from a single table to MTI, which meant I had to investigate INFORMATION_SCHEMA, find the relevant constraints and change them in the migration script before I could migrate my data.

I appreciate that migrations and emails/usernames as PKs, are probably the only use cases, and that in general you wouldn't want the onUpdate to cascade... but is there some sort of extension that can update the constraints of all tables referencing the PK of a specified table to allow the onUpdate? If not, is that possible? Perhaps this should be raised against the doctrine migrations project... I'm not sure and would value some steer.

For anyone wondering, here's how I found the relevant constraints to batch update the onUpdate behaviour during migrations in mysql:
```sql
SELECT a.CONSTRAINT_SCHEMA, a.CONSTRAINT_NAME, a.TABLE_NAME, a.COLUMN_NAME, a.REFERENCED_TABLE_NAME, a.REFERENCED_COLUMN_NAME, c.UPDATE_RULE, c.DELETE_RULE FROM KEY_COLUMN_USAGE a LEFT JOIN REFERENTIAL_CONSTRAINTS c ON a.CONSTRAINT_NAME = c.CONSTRAINT_NAME AND a.CONSTRAINT_SCHEMA=c.CONSTRAINT_SCHEMA WHERE a.CONSTRAINT_SCHEMA = '<db-name>' AND a.REFERENCED_TABLE_NAME='<table-name>'
```
Then repeat the following for each constraint whose UPDATE_RULE is RESTRICT:
```sql
ALTER TABLE <table-name> DROP FOREIGN KEY `<constraint-name>`
ALTER TABLE <table-name> ADD CONSTRAINT `<constraint-name>` FOREIGN KEY (`<column-name>`) REFERENCES `<referenced-table-name>` (`<referenced-column-name>`) ON UPDATE CASCADE ON DELETE CASCADE");
```





[DDC-2398] Add a "use namespace" like feature to DQL to have short/reusable entity classname Created: 11/Apr/13  Updated: 11/Apr/13  Resolved: 11/Apr/13

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

Type: New Feature Priority: Minor
Reporter: David Berlioz Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: Namespace, portability


 Description   

I find not always portable-friendly the use of full class path in DQL.

$query = $em->createQuery('SELECT u FROM \MyProject\Model\User u WHERE u.age > 20');

could be :

$query = $em->createQuery('USE \MyProject\Model SELECT u FROM User u WHERE u.age > 20');

or :

$query = $em->use('\MyProject\Model')->createQuery('SELECT u FROM User u WHERE u.age > 20');

And with a default namespace attached to the entity manager :

$query = $em->use()->createQuery('SELECT u FROM User u WHERE u.age > 20');



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

In strings, you always use the fully qualified class name, or an entity alias

Comment by David Berlioz [ 11/Apr/13 ]

yes and so it's not symmetrical with PHP coding...
it's unesthetic and when you do code refactoring it's harder than just managing your use "namespace";
but i've put priority to minor ;p

Comment by Marco Pivetta [ 11/Apr/13 ]

David Berlioz I'm closing this. Strings are values passed around in your system, and having their meaning depend on context is absolutely a no-go





[DDC-1931] Cache $oid and $className through method calls in UoW internals Created: 17/Jul/12  Updated: 24/Jul/12  Resolved: 24/Jul/12

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

Type: Improvement Priority: Minor
Reporter: Marco Pivetta Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: None


 Description   

As suggested by Johannes Schmitt, calls in UoW can re-use $oid and $className by passing them to the various methods of UoW internals



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

Performance gain is nearly 0... Not worth it as far as I've seen.





[DDC-1359] Deleting and inserting with unique index Created: 02/Sep/11  Updated: 09/Feb/13  Resolved: 09/Feb/13

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

Type: Bug Priority: Minor
Reporter: Rafal Radulski Assignee: Marco Pivetta
Resolution: Invalid Votes: 1
Labels: None
Environment:

MySQL



 Description   

I'm getting a database error when deleting and inserting records in a single unit of work. Consider this example:

I have a user and user_info tables. user_info stores additional data about a user as a list of key-values.
user: id, name, email, password
user_info: id, user_id, info_key, info_value

I created a unique index on user_info table: CREATE UNIQUE INDEX `user_info_key` ON `user_info` (`user_id` , `key` ) ;

Each table is represented as an Entity class.

Now, I run this code:
1. $user->removeAllInfo(); // remove old entries
2. $user->addInfo('first_name', 'John'); // add new entries
3. $this->em->flush(); // save

This causes MySQL error: "Integrity constraint violation: 1062 Duplicate entry". Doctrine ORM first persists new entities and then deletes old entities. I think the relevant code is at Doctrine/ORM/UnitOfWork :277-313. Everything works fine if I add flush() before line 2. Also, everything works fine if I change the index to non-unique.



 Comments   
Comment by Marco Pivetta [ 08/Jul/12 ]

I just got back to the UnitOfWork and (in latest master) it executes deletes as last operation (maybe to avoid cascades), and this is also documented.

In my opinion, you should do the operation of computing the changeset on your `info` collection manually...

Comment by Marco Pivetta [ 09/Feb/13 ]

Invalid usage of collection API/object graph





[DDC-3343] `PersistentCollection::removeElement` schedules an entity for deletion when relationship is EXTRA_LAZY, with `orphanRemoval` false. Created: 09/Oct/14  Updated: 05/Feb/15  Resolved: 25/Jan/15

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.2, 2.3, 2.4
Fix Version/s: 2.5, 2.4.8

Type: Bug Priority: Blocker
Reporter: Andrea Sprega Assignee: Marco Pivetta
Resolution: Fixed Votes: 0
Labels: mapping, orm

Issue Links:
Dependency
depends on DDC-3536 [GH-1281] Hotfix/#1169 extra lazy one... Resolved
depends on DDC-3544 [GH-1288] Hotfix - #1169 - extra lazy... Resolved
depends on DDC-3560 [GH-1300] [2.4] #1169 DDC-3343 one-to... Resolved
depends on DDC-3537 [GH-1282] Hotfix/#1169 extra lazy one... Resolved

 Description   

Given the following entity for which I only report the relevant association:

class Group
{
    /**
     * @ORM\OneToMany(targetEntity="User", mappedBy="group", fetch="EXTRA_LAZY")
     */
    protected $users;
    //...
}

and its inverse

class User
{
    /**
     * @ORM\ManyToOne(targetEntity="Group", inversedBy="users")
     * @ORM\JoinColumn(name="group_id", onDelete="SET NULL")
     */
    protected $group;
    //...
}

I experience a weird issue when, inside Group, I call $this->users->removeElement($user): Doctrine schedules the $user entity for deletion, no matter what (it doesn't check for the orphanRemoval attribute). Also, even re-adding the entity to a new Group before the flush() occurs doesn't prevent it from being deleted.

I believe this is a bug, since I do not see any special mention of this behavior in the documentation for extra lazy associations:
http://doctrine-orm.readthedocs.org/en/latest/tutorials/extra-lazy-associations.html.

The workaround for me has been to remove fetch="EXTRA_LAZY" from the relationship.

After digging a little bit into the source code, this seems to be the commit (and the line) that introduced this behavior:

https://github.com/doctrine/doctrine2/commit/356f5874bf81ca4e37681c233e24cc84d16e7a39#diff-108586f774fc8acb02163ed709e05e86R403

I also found this on Google:

https://groups.google.com/forum/#!topic/doctrine-user/cx_yBuoqiAE

which basically didn't help much, except for suggesting that it should be a feature when there is an orphanRemoval and/or a cascade operation in place (and that makes perfectly sense).

I set this to "critical" since (as it occurred to me) it can lead to irrecoverable data loss.

Is this effectively a bug?



 Comments   
Comment by Marco Pivetta [ 25/Jan/15 ]

Fixed via DDC-3536 and DDC-3537





[DDC-2328] [GH-597] use the extended proxy interface in the same namespace Created: 01/Mar/13  Updated: 26/Jun/14  Resolved: 03/Mar/13

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

Type: Bug Priority: Blocker
Reporter: Benjamin Eberlei Assignee: Guilherme Blanco
Resolution: Fixed Votes: 0
Labels: None


 Description   

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

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

Message:

Fix for this error:

FatalErrorException: Compile Error: Cannot use Doctrine\Common\Proxy\Proxy as Proxy because the name is already in use in .../vendor/doctrine/orm/lib/Doctrine/ORM/Proxy/ProxyFactory.php line 26



 Comments   
Comment by Marco Pivetta [ 03/Mar/13 ]

Marking as blocker - has to go in before 2.4

Comment by Benjamin Eberlei [ 03/Mar/13 ]

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

Comment by Marco Pivetta [ 03/Mar/13 ]

merged

Comment by Doctrine Bot [ 26/Jun/14 ]

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





[DDC-2229] Undefined method Created: 09/Jan/13  Updated: 22/Apr/13  Resolved: 08/Apr/13

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

Type: Bug Priority: Blocker
Reporter: Karma Dordrak (Drak) Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None

Attachments: Text File SqlWalker.patch     File SqlWalkerTest.php    

 Description   

There is an undefined method called in Doctrine\ORM\Query\SqlWalker

Fatal error: Call to undefined method Doctrine\ORM\Query\AST\PathExpression::isSimpleArithmeticExpression() in vendor\doctrine\orm\lib\Doctrine\ORM\Query\SqlWalker.php on line 2091



 Comments   
Comment by Fabio B. Silva [ 12/Jan/13 ]

Hi Karma

Could you provide the failing DQL ?

Cheers

Comment by Karma Dordrak (Drak) [ 18/Jan/13 ]

It's generating SQL from a Doctrine Collection in a proxy class. Here is a link to the example: https://github.com/zikula/core/pull/674#discussion_r2696186

The SQL being generated is

`SELECT t0.name AS name1, t0.value AS value2, t0.user_id AS user_id3 FROM users_attributes t0 WHERE t0.user_id = ?`

The ? should be the value 2, but for some reason it's not being added. I've checked the files in the stack-trace below and the right values are entering into the process, just the wrong SQL seems to be generated.

Exception Trace
#0 Exception thrown in C:\xampp\htdocs\core13\src\vendor\doctrine\dbal\lib\Doctrine\DBAL\DBALException.php, line 47.
#1 C:\xampp\htdocs\core13\src\vendor\doctrine\orm\lib\Doctrine\ORM\Persisters\BasicEntityPersister.php(1599): Doctrine\DBAL\Connection->executeQuery('SELECT t0.name ...', Array, Array)
#2 C:\xampp\htdocs\core13\src\vendor\doctrine\orm\lib\Doctrine\ORM\Persisters\BasicEntityPersister.php(1558): Doctrine\ORM\Persisters\BasicEntityPersister->getOneToManyStatement(Array, Object(Users\Entity\User))
#3 C:\xampp\htdocs\core13\src\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php(2673): Doctrine\ORM\Persisters\BasicEntityPersister->loadOneToManyCollection(Array, Object(Users\Entity\User), Object(Doctrine\ORM\PersistentCollection))
#4 C:\xampp\htdocs\core13\src\vendor\doctrine\orm\lib\Doctrine\ORM\PersistentCollection.php(224): Doctrine\ORM\UnitOfWork->loadCollection(Object(Doctrine\ORM\PersistentCollection))
#5 C:\xampp\htdocs\core13\src\vendor\doctrine\orm\lib\Doctrine\ORM\PersistentCollection.php(576): Doctrine\ORM\PersistentCollection->initialize()
#6 C:\xampp\htdocs\core13\src\lib\util\UserUtil.php(1152): Doctrine\ORM\PersistentCollection->getIterator()
#7 C:\xampp\htdocs\core13\src\lib\util\UserUtil.php(2007): UserUtil::getVars('admin', false, 'uname', false)

Comment by Fabio B. Silva [ 20/Jan/13 ]

Hi Drak,

Could you try to write a failing test case please ?

Cheers

Comment by Alexander [ 10/Feb/13 ]

ping!

Comment by Daniel Huss [ 14/Feb/13 ]

SqlWalker::walkInExpression() does this:

$sql = $this->walkArithmeticExpression($inExpr->expression)

However, $inExpr->expression could be an instance of PathExpression. The grammar allows this case:

InExpression             ::= SingleValuedPathExpression ["NOT"] "IN" "(" (InParameter {"," InParameter}* | Subselect) ")"

PathExpression and ArithmeticExpression both extend Node, but a PathExpression is not an ArithmeticExpression, and therefore it has no method isSimpleArithmeticExpression.

If you still need a failing test case, I'll write one when I get home from work.

Comment by Fabio B. Silva [ 14/Feb/13 ]

Please Daniel Huss, A test case will be very useful..

Comment by Daniel Huss [ 15/Feb/13 ]

failing test case

Comment by Daniel Huss [ 02/Apr/13 ]

Bug still present in release 2.3.3

Is someone taking care of this? It seems easy enough to fix.

Comment by Marco Pivetta [ 02/Apr/13 ]

Daniel Huss you can open a PR with the attached patch + test. Can you do it or should I take care of it?

Comment by Daniel Huss [ 02/Apr/13 ]

Please take care of it for me this time. I'd rather avoid the git setup until I have a significant contribution to make.

Comment by Benjamin Eberlei [ 08/Apr/13 ]

This is invalid, you need to set the path expression differently, this is pseudo code:

new ArtihmeticExpression(new SimpleArithmeticExpression(arithmeticsTerms => new PathExpression)));
Comment by Daniel Huss [ 22/Apr/13 ]

Could this be bug in the DQL grammar, then? If I'm not mistaken, the resolution of an InExpression cannot involve an ArithmeticPrimary non-terminal. I find the correct solution as shown by Benjamin Eberlei to be quite astonishing, since a path expression like "alias.field" is not something I'd associate with the term "arithmetic".





[DDC-2906] Atomic operations with nontransactional engines (MyISAM) Created: 11/Jan/14  Updated: 12/Jan/14  Resolved: 12/Jan/14

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

Type: Bug Priority: Critical
Reporter: Jacek Hensoldt Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: atomic, nontransactional, operations, orm,, transactions
Environment:

debian 6.0.3, php5.3.3, Mysql 5.1.49-3



 Description   

Atomic operations with nontransactional engines (MyISAM)

(INFO: this text is a supplement/clarification to http://www.doctrine-project.org/jira/browse/DDC-2905)

I know, MyISAM tables are nontransactional. That does not mean, that atomic operations are not possible.

(http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-transactions.html)

The question is how does the ORM system deal with the problem. I think its a database abstraction layer too. That means the ORM can see that the engine MyISAM is nontransactional and it chooses a different strategy to solve this task.

It makes no sense to send commands how „"SET TRANSACTION" to a nontransactional MyISAM engine (it will not work) and Doctrine ORM do that.

(for more details see my example for this behavior:
http://www.doctrine-project.org/jira/browse/DDC-2905)

An example:

(the user- and address-tables are both MyISAM-Tables)

$user = new User();
$user->setName('Mr. Test');

// OK 
$address1 = new Address();
$address1->setCity('Hamburg');
$address1->setZipcode('12345');

// entity can not be saved because zipcode is NULL
$address2 = new Address();
$address2->setCity('New York');

// OK
$address3 = new Address();
$address3->setZipcode('42000');
$address3->setCity('Solingen');

// entity can not be saved because zipcode is NULL
$address4 = new Address();
$address4->setCity('Chicago');

$user->addAddress($address1);
$user->addAddress($address2);
$user->addAddress($address3);
$user->addAddress($address4);

$em->persist($user);

try {
    $em->flush();
} catch(\Exception $e) {
    echo $e->getMessage();
}

Only the user and the first address are stored in the db, but the developer can not see that. An atomic operation is canceled (I think $em->flush() is an implicit atomic operation), we get an exception but the ORM does not go back to the original state. Now we have a system in a inconsistent state and no information about which entities are stored and which are not. Is this an expected behavior of a ORM system or database abstraction layer? I hope not.

I would now to check all entities if they are stored. In this simple example that is no problem, but for large object-graphs is this a big problem.

(sorry for my english - I try my best



 Comments   
Comment by Steve Müller [ 11/Jan/14 ]

Jacek Hensoldt The problem here is that MySQL differs from other vendors concerning support of transactions. Transactions are supported on a table engine level in MySQL, other vendors do not have different table engines. This is a MySQL specific implementation and therefore we will not add an additional abstraction layer for this. Doctrine abstracts features like transactions and foreign keys on the platform level, not based on specific table options. This does not even make sense, as it is completely non-standard and therefore does not fit into the abstraction layer.
I see the problem you have but I am afraid we cannot support this scenario in Doctrine and I would advise you to stick to InnoDB table engine when working with Doctrine in production. Otherwise it cannot be guaranteed that transactions and foreign key constraints work as expected.

Comment by Jacek Hensoldt [ 11/Jan/14 ]

Hello Steve,

thank you for your answer.

I'm a little disappointed. Our company would like to change to Doctrine ORM. We have a Database with over more than 100 MyIsam-Tables. We can not currently change all tables to InnoDB so we can not use Doctrine ORM.

I think:

  • Doctrine ORM supports official MyISAM tables (options= {"engine"="MyISAM"}
  • The command flush() is an atomic operation (UnitOfWork),
  • There is only one flush-command for all engines and vendors, so you go normally from the same behavior
  • There is absolutely no notice that the command may behave differently (be carryful when you use it with...)

That means for MySQL-MyISAM ist the abtraction layer broken.

I think it's a bad practice when a system suggests a functionality which can not meet it. Then it is mayby better the support for MyISAM completly to remove (all or nothing - the same behavior for every vendor and every table-engine).

I do not understand why Doctrine ORM can not check if all requirements are ok and why it is a problem to implement a transaction strategy for nontransactional engines. I think it is not difficult to implement.

it would be nice if Doctrine-Team could think about this problem again

Comment by Benjamin Eberlei [ 12/Jan/14 ]

There is indeed a documentation notice missing on this issue and I am sorry that you have assumed this works. But the options=

{"engine": "MyISAM"}

is not documented as well, as well is there no official statement that this is supported.

The link you provided about Ansi Transactions does not show how easy it is with MyISAM. They say you can LOCK TABLES and then write your SQL in specific ways to get it work for examples operating on one table.

You can achieve the same with Doctrine by calling the flush operation passing only one entity at a time. This will only change this one entity (and execute scheduled inserts+deletes, so its not perfect).

Supporting transactions like InnoDB and other vendors have them in code is impossible.

Comment by Benjamin Eberlei [ 12/Jan/14 ]

I added MyISAM as known limitation to the documentation:

https://github.com/doctrine/doctrine2/commit/12556e2dfeea293c65fb24000622b6327dd27e17





[DDC-2905] MySQL MyISAM Engine / Transaction rollback does not work Created: 11/Jan/14  Updated: 11/Jan/14  Resolved: 11/Jan/14

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

Type: Bug Priority: Critical
Reporter: Jacek Hensoldt Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: orm
Environment:

debian 6.0.3, MySQL 5.1.49, PHP 5.3.3-7+squeeze3 with Suhosin-Patch (cli)



 Description   

I have two simple entities ( user 1:n address)

<?
/**
 * @Entity @Table(name="users", options={"engine"="MyISAM"})
 **/
class User {
    /** @Id @Column(type="integer") @GeneratedValue **/
    protected $id;
    /** @Column(type="string") **/
    protected $name;

    /**
     * @OneToMany(targetEntity="Address", mappedBy="user", cascade={"persist"})
     * @var Address[]
     **/
    protected $addresses = null;

    public function __construct()
    {
        $this->addresses = new ArrayCollection();
    }

    public function getId() {
        return $this->id;
    }

    public function setName($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }

    public function addAddress(Address $address) {
        $this->addresses[] = $address;
        $address->setUser($this);
    }
}

 * @Entity @Table(name="addresses", options={"engine"="MyISAM"})
 **/
class Address {
    /** @Id @Column(type="integer") @GeneratedValue **/
    protected $id;
    /** @Column(type="string") **/
    protected $zipcode;
    /** @Column(type="string") **/
    protected $city;

    /**
     * @ManyToOne(targetEntity="User", inversedBy="addresses")
     * @var User;
     **/
    protected $user = null;

    /**
     * @return mixed
     */
    public function getId() {
        return $this->id;
    }
    /**
     * @return mixed
     */
    public function getCity() {
        return $this->city;
    }

    /**
     * @param mixed $zipcode
     */
    public function setZipcode($zipcode) {
        $this->zipcode = $zipcode;
    }

    /**
     * @return mixed
     */
    public function getZipcode() {
        return $this->zipcode;
    }

    public function setUser(User $user) {
        //$user->addAddress($this);
        $this->user = $user;
    }

    public function getUser() {
        return $this->user;
    }

}

?>

When i do this, then i get an exception:

$user = new User();
$user->setName('Mr. Test');

$address = new Address();
$address->setCity('New York');

$user->addAddress($address);

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


// Exception:Integrity constraint violation: 1048 Column 'zipcode' cannot be null'

That's okay, but the address-entity needs a zipcode.

The output from sqlLogger looks like this:

"START TRANSACTION" INSERT INTO users (name) VALUES (?)
array
  1 => string 'Mr. Test' (length=5)
array
  1 => string 'string' (length=6)
INSERT INTO addresses (zipcode, city, street, user_id) VALUES (?, ?, ?, ?)
array
  1 => null
  2 => string 'New York' (length=8)
  3 => null
  4 => int 1
array
  1 => string 'string' (length=6)
  2 => string 'string' (length=6)
  3 => string 'string' (length=6)
  4 => string 'integer' (length=7)
"ROLLBACK"

 

That Problem is, that the transaction is broken and the rollback operation does not work. I get a new user without a address:

mysql> select * from users;
+----+----------+
| id | name     |
+----+----------+
|  1 | Mr. Test |
+----+----------+

mysql> select * from addresses;
Empty set (0.00 sec)

 



 Comments   
Comment by Benjamin Eberlei [ 11/Jan/14 ]

This is not an issue with Doctrine, MyISAM does not support rollbacks. Use InnoDB instead.





[DDC-2204] Order by With Equals is not supported Created: 17/Dec/12  Updated: 20/Apr/15  Resolved: 22/Dec/12

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: DQL
Affects Version/s: 2.3
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: Ilya Biryukov Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: dql
Environment:

SQL construct tested on postgres 9.0, mysql 5.5, and sqlite 3.


Attachments: File Language.sql    

 Description   

The sample query (I want to bring a specific item to the top of the list).
mysql> select * from Language order by name='English' desc, name asc limit 5;
------------+

id name

------------+

82 English
73 Albanian
74 Arabic
75 Armenian
76 Bengali

------------+
5 rows in set (0.00 sec)

In theory, the code below should generate the same query.
$repository->createQueryBuilder('p')
->addOrderBy("p.name='english'", 'desc')
->addOrderBy('p.name', 'asc');

In practice, an exception is thrown.
Doctrine\ORM\Query\QueryException: [Syntax Error] line 0, col 67: Error: Expected end of string, got '=' (uncaught exception) at /vendor/doctrine/orm/lib/Doctrine/ORM/Query/QueryException.php line 44

Attached, SQL dump for the table & data



 Comments   
Comment by Benjamin Eberlei [ 22/Dec/12 ]

Its supported by including the condition in the SELECT clause, aliasing it, then using it. You might need to use "AS HIDDEN name" to prevent it from appearing in the result

Comment by Alexey Kosov [ 20/Apr/15 ]

It does not actually work.

http://stackoverflow.com/questions/25761989/doctrine-select-statement-using-equals-not-accepted





[DDC-2162] Undefined index: joinColumns in ManyToMany association Created: 22/Nov/12  Updated: 08/Sep/13  Resolved: 08/Sep/13

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: DQL, Mapping Drivers
Affects Version/s: 2.3, Git Master
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: Vyacheslav Slinko Assignee: Benjamin Eberlei
Resolution: Incomplete Votes: 0
Labels: None


 Description   

My classes: https://gist.github.com/4131893

When calling PageRepository::findByTags i get

Notice: Undefined index: joinColumns in vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 1494



 Comments   
Comment by Vyacheslav Slinko [ 22/Nov/12 ]

Found a problem: PageRepository not configured for Page entity





[DDC-1831] Problem while implement a relation many to many with columns names starting with caps Created: 21/May/12  Updated: 06/Jul/12  Resolved: 06/Jul/12

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

Type: Bug Priority: Critical
Reporter: Pablo Minetti Assignee: Fabio B. Silva
Resolution: Fixed Votes: 0
Labels: None

Attachments: Text File defect_patch.txt    

 Description   

Hi, In my team we are implementing a solution that involves make a relation many to many.

The problem is that the columns names of the middle table start with caps.

we make correction to ORM to solve this problem. I attach to you the files modify.



 Comments   
Comment by Fabio B. Silva [ 05/Jun/12 ]

Hi Pablo,

I'm working on a quote patch right now.
I think that will fix a lot of quote issues.

Could you attach a test for this case please ?

Comment by Benjamin Eberlei [ 05/Jul/12 ]

Fabio, any stats on this one? Is it fixed through your change?

Comment by Fabio B. Silva [ 05/Jul/12 ]

There is no answers from Pablo,

I think this is fixed by quote strategy, also DDC-1850
but without entities or tests is hard to know if are really fixed.

if we don't get any feedback from Pablo, I think both could be closed.

Comment by Benjamin Eberlei [ 06/Jul/12 ]

No feeback given and a fix was pushed to master. Please reopen if problems persist with master + custom quoting strategy.





[DDC-1651] APC query caching fails when an entity is bound to a query parameter. Created: 14/Feb/12  Updated: 18/Feb/12  Resolved: 18/Feb/12

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: DQL, ORM
Affects Version/s: 2.1.6
Fix Version/s: 2.2.1

Type: Bug Priority: Critical
Reporter: Jonathan Robinson Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: None
Environment:

Debian, Php 5.3, APC 3.1.9



 Description   

When an entity is bound as a query parameter, query caching with APC fails with error message:

Catchable fatal error: Object of class XXX could not be converted to string in /libs/doctrine-orm/Doctrine/DBAL/Connection.php on line 1081

If I bind with entity's primary key field, everything works fine.



 Comments   
Comment by Benjamin Eberlei [ 18/Feb/12 ]

Fixed and merged into 2.2 branch.

A rebase onto the 2.1.x branch would take a rewrite, since the code is completly new and since there is a simple workaround ($entity->getId()) when binding i will not backported it into the 2.1.x branch.

https://github.com/doctrine/doctrine2/commit/6cd82d77f5e581b3d21c60c5cb5e6c5042a3ff9b





[DDC-1535] Association method createEntity Created: 13/Dec/11  Updated: 15/Dec/11  Resolved: 15/Dec/11

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

Type: Bug Priority: Critical
Reporter: André Ribeiro de Miranda Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None
Environment:

php 5.3.8



 Description   

File: ORM/UnitOfWork.php
Method: function createEntity

within the
if ($assoc ['inversedBy'] && $assoc['type'] & ClassMetadata:ONE_TO_ONE) {

The excerpt below is thus
$targetClass->reflFields[$inverseAssoc['fieldName']]->setValue($newValue, $entity);

And should be well
$targetClass->reflFields[$inverseAssoc['fieldName']]->setValue ($entity, $newValue);



 Comments   
Comment by Guilherme Blanco [ 14/Dec/11 ]

Are you experiencing any type of issues with this?
If positive, please share your models and the script that this issue is happening.

This specific line does the inverse side association assignment of newly created node. I don't see anything wrong with that line.

Comment by Benjamin Eberlei [ 15/Dec/11 ]

This code is valid. It sets the other side of an association on a bidirectional one to one.





[DDC-1533] ResultSetMap don't work with aliases when using joined entites Created: 13/Dec/11  Updated: 15/Dec/11  Resolved: 15/Dec/11

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

Type: Bug Priority: Critical
Reporter: Bostjan Oblak Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None
Environment:

windows 7, php 5.3.6



 Description   

When using entityNamespace and ResultSetMapping with joined entites you get hydration error.

Example:
EntityNamespace is set to "Project\Model"

I have result set mapping:
->addEntityResult(':Entity', 'e')
->addJoinedEntityResult(':OtherEntity', 'oe', 'e', 'other')

you will get error:

Notice: Undefined index: Projet\Model\OtherEntity in Doctrine\ORM\Internal\Hydration\ObjectHydrator.php on line 371

solution is to use full names for entites:
->addEntityResult('Project\Model\Entity', 'e')
->addJoinedEntityResult('Project\Model\OtherEntity', 'oe', 'e', 'other')



 Comments   
Comment by Benjamin Eberlei [ 15/Dec/11 ]

Class names in strings are always full qualified expect for the metadata target entities. This is expected.

I don't think a check makes sense here, also because we don't have access to a utility that allows for checks.





[DDC-1505] EntityManager->find returning null for entity on the inverse side of a OneToOne association Created: 23/Nov/11  Updated: 18/Dec/11  Resolved: 18/Dec/11

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: Git Master
Fix Version/s: 2.x, Git Master

Type: Bug Priority: Critical
Reporter: Chris Richard Assignee: Alexander
Resolution: Fixed Votes: 0
Labels: None


 Description   

BasicEntityPersister.getJoinSQLForJoinColumns treats joinColumn nullable setting as defaulting to false:

if(isset($joinColumn['nullable']) && $joinColumn['nullable'])

{ return 'LEFT JOIN'; }

I think it should be:

if(!isset($joinColumn['nullable']) || $joinColumn['nullable']){ return 'LEFT JOIN'; }

 Comments   
Comment by Benjamin Eberlei [ 15/Dec/11 ]

Assigned to asm

Comment by Benjamin Eberlei [ 18/Dec/11 ]

This issue is referenced in Github Pull-Request GH-226
https://github.com/doctrine/doctrine2/pull/226

Comment by Alexander [ 18/Dec/11 ]

Should be fixed as soon as this is pulled:
https://github.com/doctrine/doctrine2/pull/226

Comment by Benjamin Eberlei [ 18/Dec/11 ]

Related Pull Request was closed: https://github.com/doctrine/doctrine2/pull/226





[DDC-1300] Can't fetch entities from IdentityMap when using a foreign keys as identifiers Created: 27/Jul/11  Updated: 06/Aug/11  Resolved: 06/Aug/11

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.1
Fix Version/s: 2.1.1

Type: Bug Priority: Critical
Reporter: Van Hauwaert Bert Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: None


 Description   

Given the follow SQL structure:

CREATE TABLE `foo` (
  `fooID` int(11) NOT NULL AUTO_INCREMENT,
  `fooReference` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`fooID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='module=bug';

CREATE TABLE `fooLocale` (
  `fooID` int(11) NOT NULL,
  `locale` varchar(5) NOT NULL DEFAULT '',
  `title` varchar(150) DEFAULT NULL,
  PRIMARY KEY (`fooID`,`locale`),
  KEY `fk_foo2` (`fooID`),
  CONSTRAINT `fk_table1_foo2` FOREIGN KEY (`fooID`) REFERENCES `foo` (`fooID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module=bug';

INSERT INTO `foo` (`fooID`, `fooReference`)
VALUES
	(1, 'foo1');

INSERT INTO `fooLocale` (`fooID`, `locale`, `title`)
VALUES
	(1, 'en_GB', 'Foo title test');

and the following models:

use Doctrine\ORM\Mapping as ORM;

/**
 * Model for foo
 *
 * @category Application
 * @package Bug
 * @subpackage Model
 * @ORM\Table(name="foo")
 * @ORM\Entity
 */
class Bug_Model_Foo
{
	/**
	 * @var integer fooID
	 * @ORM\Column(name="fooID", type="integer", nullable=false)
	 * @ORM\GeneratedValue(strategy="IDENTITY")
	 * @ORM\Id
	 */
	protected $_fooID = null;

	/**
	 * @var string fooReference
	 * @ORM\Column(name="fooReference", type="string", nullable=true, length=45)
	 */
	protected $_fooReference = null;

	/**
	 * @ORM\OneToMany(targetEntity="Bug_Model_FooLocale", mappedBy="_foo",
	 * cascade={"persist"})
	 */
	protected $_fooLocaleRefFoo = null;

	/**
	 * Constructor
	 *
	 * @param array|Zend_Config|null $options
	 * @return Bug_Model_Foo
	 */
	public function __construct($options = null)
	{
		$this->_fooLocaleRefFoo = new \Doctrine\Common\Collections\ArrayCollection();
	}

}
use Doctrine\ORM\Mapping as ORM;

/**
 * Model for fooLocale
 *
 * @category Application
 * @package Bug
 * @subpackage Model
 * @ORM\Table(name="fooLocale")
 * @ORM\Entity
 */
class Bug_Model_FooLocale
{
	/**
	 * @ORM\ManyToOne(targetEntity="Bug_Model_Foo")
	 * @ORM\JoinColumn(name="fooID", referencedColumnName="fooID")
	 * @ORM\Id
	 */
	protected $_foo = null;

	/**
	 * @var string locale
	 * @ORM\Column(name="locale", type="string", nullable=false, length=5)
	 * @ORM\Id
	 */
	protected $_locale = null;

	/**
	 * @var string title
	 * @ORM\Column(name="title", type="string", nullable=true, length=150)
	 */
	protected $_title = null;

}

Execute the following DQL 2 times:

$query = $entityManager->createQuery('
			SELECT 
				f, fl 
			FROM 
				Bug_Model_Foo f 
			JOIN 
				f._fooLocaleRefFoo fl');
		return $query->getResult();

The first time, you won't have any issues.
The second time, when the data will be fetched from the identityMap, you won't find it because there is something wrong with the identities and you will get the following warning

( ! ) Notice: Undefined index: _foo in /var/www/vhost/core/htdocs/externals/Doctrine/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php on line 217
Call Stack
#	Time	Memory	Function	Location
1	0.0002	337752	{main}( )	../index.php:0
2	0.0848	7268724	Zend_Application->run( )	../index.php:26
3	0.0848	7268724	Zend_Application_Bootstrap_Bootstrap->run( )	../Application.php:366
4	0.0850	7268796	Zend_Controller_Front->dispatch( )	../Bootstrap.php:97
5	0.0908	7900416	Zend_Controller_Dispatcher_Standard->dispatch( )	../Front.php:954
6	0.0967	8209564	Zend_Controller_Action->dispatch( )	../Standard.php:295
7	0.0967	8213912	Bug_IndexController->indexAction( )	../Action.php:513
8	0.1936	11391900	Bug_Service_Bug->getFooLocaleList( )	../IndexController.php:35
9	0.1936	11394088	Doctrine\ORM\AbstractQuery->getResult( )	../Bug.php:41
10	0.1936	11394296	Doctrine\ORM\AbstractQuery->execute( )	../AbstractQuery.php:392
11	0.1945	11397960	Doctrine\ORM\Internal\Hydration\AbstractHydrator->hydrateAll( )	../AbstractQuery.php:594
12	0.1946	11398656	Doctrine\ORM\Internal\Hydration\ObjectHydrator->_hydrateAll( )	../AbstractHydrator.php:99
13	0.1946	11399876	Doctrine\ORM\Internal\Hydration\ObjectHydrator->_hydrateRow( )	../ObjectHydrator.php:140
14	0.1949	11405584	Doctrine\ORM\Internal\Hydration\ObjectHydrator->_getEntityFromIdentityMap( )	../ObjectHydrator.php:326

With the invalid key, it is not possible to get the entity from the identityMap.



 Comments   
Comment by Benjamin Eberlei [ 06/Aug/11 ]

I could reproduce this, working on a fix.

Comment by Benjamin Eberlei [ 06/Aug/11 ]

Fixed





[DDC-3866] Embedded value objects with single table inheritance not working Created: 05/Aug/15  Updated: 05/Aug/15  Resolved: 05/Aug/15

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM, Tools
Affects Version/s: 2.5
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Geert Eltink Assignee: Steve Müller
Resolution: Duplicate Votes: 0
Labels: None
Environment:

php 5.6, mysql 5.7, symfony 2.7



 Description   

When updating the schema I get this:

> php app/console doctrine:schema:update --force

[ReflectionException]
Property ContentBundle\Entity\PageContent::$guid does not exist

All relevant classes are located here: https://gist.github.com/xtreamwayz/84159f006616b4029623

Without the single table inheritance it works perfectly and it creates the correct table structure. But when enabling it I get the error when trying to create the schema. I don't know if this is simply not possible, my code is wrong or it is a bug.



 Comments   
Comment by Geert Eltink [ 05/Aug/15 ]

Please close this issue and blame my crappy internet provider, it's the same as #DDC-3867.

Comment by Geert Eltink [ 05/Aug/15 ]

See #DDC-3867





[DDC-3553] Create a QueryBuilder from a Query/DQL Created: 01/Feb/15  Updated: 01/Feb/15  Resolved: 01/Feb/15

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

Type: Documentation Priority: Major
Reporter: Dries De Peuter Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: querybuilder


 Description   

Hi,

I am searching for a way to create a QueryBuilder from an existing Query or a DQL string.

Can I currently do this?

If this is not the case. I would love to create this but I don't see how to parse the DQL into parts.



 Comments   
Comment by Marco Pivetta [ 01/Feb/15 ]

.

Not an issue

Note that the QueryBuilder just assembles strings: there is currently no way to transform DQL into a query builder, as the operation is not bijective.

Comment by Dries De Peuter [ 01/Feb/15 ]

I understand. Is their any way you would suggest allowing a DQL to be altered/extended.





[DDC-3543] How to map and use a DB View from Doctrine2 Created: 26/Jan/15  Updated: 26/Jan/15  Resolved: 26/Jan/15

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers, ORM
Affects Version/s: 2.4.7
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Reynier Perez Mira Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: None


 Description   

I have a view on nomencladores schema called obtenerPaisesPorFabricanteProductoSolicitud. This is the content for the view:

    SELECT
    	ps.id AS psid,
    	ps.nombre,
    	fps.id AS fpsid
    FROM
    	(
    		(
    			nomencladores.pais ps
    			JOIN nomencladores.pais_fabricante_producto_solicitud pfps ON ((pfps.pais_id = ps.id))
    		)
    		JOIN negocio.fabricante_producto_solicitud fps ON (
    			(
    				pfps.fabricante_producto_solicitud_id = fps.id
    			)
    		)
    	);

I'm trying to map the view as follow:

    use Doctrine\ORM\Mapping as ORM;
    
    /**
     * @ORM\Entity
     * @ORM\Table(name="nomencladores.obtenerPaisesPorFabricanteProductoSolicitud", schema="nomencladores")
     */
    class ObtenerPaisesPorFabricanteProductoSolicitud
    {
        /**
         * @ORM\Id
         * @ORM\Column(name="psid", type="integer", nullable=false, unique=true)
         */
        protected $ps;
    
        /**
         * @ORM\Column(name="fpsid", type="integer")
         */
        protected $fps;
    
        /**
         * @ORM\Column(name="nombre", type="string")
         */
        protected $nombre;
    
        public function getPs()
        {
            return $this->ps;
        }
    
        public function getFps()
        {
            return $this->fps;
        }
    
        public function getNombre()
        {
            return $this->nombre;
        }
    }

But any time I run this code on it:

    $ent = $em->getRepository("AppBundle:ObtenerPaisesPorFabricanteProductoSolicitud")->findBy(
        array(
            "fps" => $entF->getId()
        )
    );

I got this result:

An exception occurred while executing 'SELECT t0.psid AS psid1,
t0.fpsid AS fpsid2, t0.nombre AS nombre3 FROM
nomencladores.obtenerPaisesPorFabricanteProductoSolicitud t0 WHERE
t0.fpsid = ?' with params [22]:
SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "nomencladores.obtenerpaisesporfabricanteproductosolicitud" does not
exist LINE 1: ...d1, t0.fpsid AS fpsid2, t0.nombre AS nombre3 FROM
nomenclado...

If I remove the annotations then the error transform on this:

Class "AppBundle\Entity\ObtenerPaisesPorFabricanteProductoSolicitud" is not a valid entity or mapped super class."

Why Doctrine2 or Symfony tries to execute the query instead go through the view? How I can execute the view from Symfony2/Doctrine2 side?



 Comments   
Comment by Marco Pivetta [ 26/Jan/15 ]

Nothing wrong here: the SQL generated by the ORM is correct, but your view definition is wrong: try running the select in console, manually.





[DDC-3342] Join with child tables Created: 09/Oct/14  Updated: 19/Oct/14  Resolved: 19/Oct/14

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

Type: New Feature Priority: Major
Reporter: Thomas Lallement Assignee: Marco Pivetta
Resolution: Duplicate Votes: 0
Labels: None

Issue Links:
Duplicate
duplicates DDC-16 DQL Ignores properties of subclasses Closed

 Description   

Hi,

It could help a lot if we could simply join parent table with childs when the inheritance type is JOINED.

For example if you need to add clauses on child properties. For the moment we need to create sub queries to add clauses in it.



 Comments   
Comment by Thomas Lallement [ 09/Oct/14 ]

It would also be possible and useful to be able to sort on the DiscriminatorColumn





[DDC-3304] [EntityGenerator] Embeddables properties and methods are broken Created: 11/Sep/14  Updated: 19/Oct/14  Resolved: 12/Sep/14

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

Type: Improvement Priority: Major
Reporter: Phansys Assignee: Marco Pivetta
Resolution: Fixed Votes: 0
Labels: embeddables, entityGenerator, generation, mapping, orm

Issue Links:
Dependency
depends on DDC-3307 [GH-1135] [DDC-3304] Add support for ... Resolved

 Description   

EntityGenerator creates broken properties for embeddables. Given the example classes exposed in http://docs.doctrine-project.org/en/latest/tutorials/embeddables.html (User, Address), EntityGenerator creates wrong associations in User entity. Instead of this:

```php
/**

  • Address
    *
  • @var Address
    */
    private $address;
    ```

I get this:
```php
/**

  • Address.street
    *
  • @var string
    */
    private $address.street;
    /**
  • Address.postalCode
    *
  • @var string
    */
    private $address.postalCode;
    /**
  • Address.city
    *
  • @var string
    */
    private $address.city;
    /**
  • Address.country
    *
  • @var string
    */
    private $address.country;
    ```

And the same for its getters and setters.
I'll try to do a PR when I found a way to solve this.



 Comments   
Comment by Steve Müller [ 11/Sep/14 ]

Phansys which version of ORM are you using? If you are using latest master, this might be related to PR: https://github.com/doctrine/doctrine2/pull/1105
It looks like it broke the EntityGenerator. Can you confirm?

Comment by Phansys [ 11/Sep/14 ]

Confirmed @deeky666, on rev d9b43dc6492b163fc46f40c0555e2a7015ef5b68 (https://github.com/doctrine/doctrine2/tree/d9b43dc6492b163fc46f40c0555e2a7015ef5b68).
Thank you!

Comment by Phansys [ 11/Sep/14 ]

I've tried with rev 8a3def097f9ebd773ee298f5611ce8bf7007fa7e (previous to PR#1105) and the result is the same broken structure.

Comment by Steve Müller [ 11/Sep/14 ]

Phansys thanks for your feedback. I will see if I have time tomorrow to look into this issue.

Comment by Steve Müller [ 12/Sep/14 ]

Had a quick look into the issue and recognized that embeddables are not taken into account at all at the moment. Working on a solution...

Comment by Steve Müller [ 12/Sep/14 ]

Patch provided in PR: https://github.com/doctrine/doctrine2/pull/1135

Comment by Doctrine Bot [ 12/Sep/14 ]

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

Comment by Doctrine Bot [ 12/Sep/14 ]

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

Comment by Steve Müller [ 12/Sep/14 ]

Fixed in commit: https://github.com/doctrine/doctrine2/commit/f12c311a795b69a5f4853b079b3f8ad2c9867181

Comment by Phansys [ 13/Sep/14 ]

Thanks Steve Müller.

Comment by Doctrine Bot [ 19/Oct/14 ]

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





[DDC-3299] Possibility to define Entities in separate Bounded Context Created: 09/Sep/14  Updated: 13/Sep/14  Resolved: 10/Sep/14

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

Type: Improvement Priority: Major
Reporter: Piotr Deszyński Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: schematool


 Description   

It would be great to have a possibility to define two entities in different Bounded Context. For now it's possible without a problem to use such an Entities but it's impossible to use schema tools, when two separate Entities map to the same table.



 Comments   
Comment by Marco Pivetta [ 10/Sep/14 ]

This feature would break a very important invariant existing in the ORM: only one entity for a particular identifier existing in memory at any time.

This cannot be implemented, and actually goes against the rules imposed by the ORM.

The only solution to this problem would be to have a writable view, and mapping an entity to it, and an entity to the actual table: that's still making some of the transactions in your application very risky.

Comment by Piotr Deszyński [ 12/Sep/14 ]

But wouldn't it be possible to implement it really similar to single table inheritance but without a DiscriminatorColumn? Which instance would be returned would depend on the repository used.

Comment by Marco Pivetta [ 13/Sep/14 ]

Piotr Deszyński that wouldn't prevent having two instances of the same entity in memory, which is a problem.





[DDC-3207] Paginator does not count according to query max results Created: 05/Jul/14  Updated: 08/Jul/14  Resolved: 06/Jul/14

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

Type: Bug Priority: Major
Reporter: Draeli Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: orm
Environment:

Windows



 Description   

I use Doctrine\ORM\Tools\Pagination\Paginator to have an paginate object and use like this :

$paginator = new Paginator($query);
$paginator->getQuery()->setFirstResult(0)->setMaxResults(1);

In this case when I do a count on object result and have "int 2" in spite I expected "int 1".

I look the class and find may be the problem, why there is this ?

$countQuery->setFirstResult(null)->setMaxResults(null);

in "count" method.

If I remove this line, expected result appear.



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

The paginator will always count over the entire resultset of your query, since that is its primary purpose together with providing iteration over slices of the resultset.

Comment by Draeli [ 06/Jul/14 ]

I can understand the global count but for example (and now I saw why the line I descripbe above is) in case I use with Twig for iterate (with

{% for %}

syntax), the length return by object|length not appear to be what expected because if the goal of Pagination is to expose method to work more easier with object, I supose you must only work with current page object result and the total count must be expose in method but not directly as iterator count result.

Comment by Marco Pivetta [ 06/Jul/14 ]

Draeli the count($paginator) will give you the total items. The current offset and limit can be trusted to get the items in the current page.

Comment by Draeli [ 06/Jul/14 ]

I understood about the count($paginator) but that's not the only point.
Why when I do {{ loop.last }} (inside for loop) this give me "false" in spite it is the last one for the current page ?
Sorry to insist but as simple user of Sf2/Twig/Doctrine I don't understand this logic :/
(or maybe I'm not enough clear)

Comment by Draeli [ 06/Jul/14 ]

To explain more, actually I do a request and give me object :

$paginator = new Paginator($query);
$paginator->getQuery()->setFirstResult(0)->setMaxResults(5);
$Articles = $paginator;

and in the view

{{ dump(Articles|length) }} {# here "int 23" for example in this case because result without limit is 23, ok I understand #}
{% for anArticle in Articles %}
{{ dump(loop.first) }} {# as expected here "true" for the first and false for other #}
{{ dump(loop.last) }} {# always "false" even for the fifth result who is suppose to bu "true" #}
{{ dump(loop.length) }} {# here return always "int 23" in spite expected 5 #}
{% endfor %}
{# for display my 5 object in spite loop.last and loot.length not expected result #}

As you see something is not expected.

Comment by Marco Pivetta [ 06/Jul/14 ]

We can't provide support for Twig integration. That seems to be a Twig specific issue with how twig deals with loops, nothing related with the ORM. Instead, ask on http://stackoverflow.com/

Comment by Draeli [ 06/Jul/14 ]

Ok thank you for your answer, I'm going to ask, just I signal I put question relative to this for Twig here :
https://github.com/symfony/symfony/issues/11316
Have a good day

Comment by Christophe Coevoet [ 07/Jul/14 ]

Iterate over paginator.iterator in Twig, and loop.last will give you wht you want

Comment by Draeli [ 08/Jul/14 ]

A really big thank you Christophe It's work





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

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

Type: Bug Priority: Major
Reporter: Andy hunt Assignee: Marco Pivetta
Resolution: Invalid 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

Comment by Marco Pivetta [ 18/Aug/14 ]

Resolving as invalid: this seems to be a misuse in my opinion.





[DDC-3033] Regression in computeChangeSets (ManyToMany relation) Created: 17/Mar/14  Updated: 23/Mar/14  Resolved: 23/Mar/14

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: Git Master
Fix Version/s: 2.5, 2.4.3

Type: Bug Priority: Major
Reporter: Thomas Lallement Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: orm
Environment:

Ubuntu



 Description   

I discover that computeChangeSet doesn't compute as before from this commit:

https://github.com/doctrine/doctrine2/commit/53a5a48aed7d87aa1533c0bcbd72e41b686527d8#commitcomment-5696972

From this commit, I have a bug when using KNP doctrine behaviors (with a custom code to log the changes on Entities in Database) because when I call the following code, it doesn't return the same changeSet as before:

$uow->computeChangeSet($classMetadata, $entity);
$changeSet = $uow->getEntityChangeSet($entity);

Before the "ManyToMany" properties were not in the $changeSet. Now there are with original value NULL -> new value Doctrine\ORM\PersistentCollection. Is it normal?






[DDC-2843] SchemaTool update SQL always contains queries to set default value on columns, even if they haven't changed. Created: 07/Dec/13  Updated: 22/Dec/13  Resolved: 22/Dec/13

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: 2.2.3
Fix Version/s: 2.5, 2.4.2

Type: Bug Priority: Major
Reporter: Kamil Kokot Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: dbal


 Description   

For example, I've got this schema:

Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="tbl_company")
 * @ORM\Entity
 */
class Company
{
    /**
     * @ORM\Column(name="verified", type="boolean", nullable=false, options={"default"=false})
     */
    protected $verified = false;
}

I introduce column "verified", which is not nullable and this way I want all old entries to automatically update - it works. Then, I'm working and doing another updates. In every update SQL there is ALTER query, though default value haven't been changed since I had created it.

ALTER TABLE tbl_company ALTER verified SET  DEFAULT 'false';

Shouldn't it check for changes and apply this query only if default value is changed? When I'm creating migrations, there are about ~60 queries which doesn't change anything and ex. 1 which does - it's very distracting.



 Comments   
Comment by Benjamin Eberlei [ 14/Dec/13 ]

This is an issue in DBAL. This should be reproduced using the \Doctrine\DBAL\Schema\Table API and then fixedn on DBAL.





[DDC-2415] CustomIdGenerator not inherited from MappedSuperclass Created: 25/Apr/13  Updated: 08/Sep/13  Resolved: 27/Apr/13

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.3.3
Fix Version/s: 2.4

Type: Bug Priority: Major
Reporter: Sebastian Calvo Assignee: Fabio B. Silva
Resolution: Fixed Votes: 0
Labels: orm


 Description   

I had a problem with a CUSTOM id generation mapping definition.
I have an abstract class and @MappedSuperclass which defines the id column as:

/**

  • @ORM\Id
  • @ORM\Column(name="ID", type="integer")
  • @ORM\GeneratedValue(strategy="CUSTOM")
  • @ORM\CustomIdGenerator(class="Infoil\Extensions\ExtensionsBundle\DoctrineIdGenerator\ZafiroIdGenerator")
  • @var int $id
    */
    The problem is that subclasses doesn't inherits the CustomIdGenerator annotation. I have traced the problem up to ClassMetadataFactory::doLoadMetadata.
    I had to change the second inner if statement as

if ($parent->isMappedSuperclass) {
$class->setCustomRepositoryClass($parent->customRepositoryClassName);
$class->setCustomGeneratorDefinition($parent->customGeneratorDefinition); <<<<< LINE ADDED
}
to allow subclasses inherit the customGenerationdefinition.

Aside, the docblock annotation help doesn't includes the CustomIdGenerator tag.



 Comments   
Comment by Fabio B. Silva [ 27/Apr/13 ]

Fixed : https://github.com/doctrine/doctrine2/commit/d513e0f084eb4e67ccb42877b28a27d47a561665





[DDC-2394] QueryExpressionVisitor has no implementation of Comparison::CONTAINS Created: 08/Apr/13  Updated: 03/Jun/14  Resolved: 14/Apr/13

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

Type: Bug Priority: Major
Reporter: Boris Guéry Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: criteria, expression, orm, query
Environment:

n/a



 Description   
Use case
$criteria = Criteria::create();
$criteria
    ->andWhere(
        $criteria->expr()->contains('r.body', 'foo')
    )
;

$entities = $repo->createQueryBuilder()->addCriteria($criteria)->getQuery()->getResult();

Throws the following exception:

RuntimeException: Unknown comparison operator: CONTAINS

I except it to properly handle the CONTAINS comparison and result in a LIKE operator.

-------

I added a failing test case & a fix there: https://github.com/borisguery/doctrine2/tree/DDC-2394



 Comments   
Comment by Benjamin Eberlei [ 14/Apr/13 ]

This was added in 2.4, you are probably using Collections 1.1 with ORM 2.3, where this occurs.

Comment by Matthieu Napoli [ 16/Sep/13 ]

Apparently it wasn't, I'm on 2.4 and still get the exception.

I submitted a PR: https://github.com/doctrine/doctrine2/pull/791

Comment by Doctrine Bot [ 11/Oct/13 ]

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

Comment by Matthias Althaus [ 27/May/14 ]

As this issue confused me, I took a look into it and the reason seems to be that there's no current release of doctrine/orm including this bugfix. It's not part of the current v2.4.2 tag:

https://github.com/doctrine/doctrine2/blob/v2.4.2/lib/Doctrine/ORM/Query/QueryExpressionVisitor.php
https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Query/QueryExpressionVisitor.php

We'd be really happy to get a new bugfix release.

Running those lib versions:

doctrine/annotations v1.1.2 Docblock Annotations Parser
doctrine/cache v1.3.0 Caching library offering an object-oriented API for many cache b...
doctrine/collections v1.2 Collections Abstraction library
doctrine/common v2.4.2 Common Library for Doctrine projects
doctrine/data-fixtures v1.0.0 Data Fixtures for all Doctrine Object Managers
doctrine/dbal v2.4.2 Database Abstraction Layer
doctrine/doctrine-bundle v1.2.0 Symfony DoctrineBundle
doctrine/doctrine-fixtures-bundle v2.2.0 Symfony DoctrineFixturesBundle
doctrine/inflector v1.0 Common String Manipulations with regard to casing and singular/p...
doctrine/lexer v1.0 Base library for a lexer that can be used in Top-Down, Recursive...
doctrine/orm v2.4.2 Object-Relational-Mapper for PHP

Comment by Marco Pivetta [ 27/May/14 ]

Matthias Althaus this is a new feature, it won't be backported as bugfix.

Comment by Matthieu Napoli [ 27/May/14 ]

Marco Pivetta I would rather say it's a bug because the feature works with ArrayCollection. It was something missing in the implementation in the ORM. The feature is offered by the interface of the Criteria, so the ORM implementation should support it (else the Collection abstraction is useless).

Comment by Marco Pivetta [ 27/May/14 ]

Matthieu Napoli the criteria expressions support depends on the visitor implementation.
They are not interfaced, and custom expression types are also accepted.

Comment by Matthieu Napoli [ 27/May/14 ]

Beyond code interface, I rather mean "contract" between the library and the user.

The criteria's purpose is a query API that works both on persistent and non-persistent collections: it abstracts the persistence away. By having differences in implementation, the main purpose of the criteria is lost, which IMO is a bug.

Comment by Marco Pivetta [ 27/May/14 ]

Matthieu Napoli there are actually various implementations that just don't support many of the operations (wrote some cache-based adapters and some Zend\Db ones as well). It's just an unsupported case in this version, it is not a bug.

Comment by Matthias Althaus [ 03/Jun/14 ]

I can understand both sides, but it's a pity that the QueryExpressionVisitor has such issues with the Criteria API (which is basically quite nice). We've just build some complex filter management around the Criteria API and now it seems more and more like a bad decision.





[DDC-2383] Foreign relations on primary keys don't work on more than two entities (like Foo<>Bar<>Baz) Created: 01/Apr/13  Updated: 14/Apr/13  Resolved: 14/Apr/13

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.3, 2.4
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Jacek Jędrzejewski Assignee: Benjamin Eberlei
Resolution: Can't Fix Votes: 0
Labels: hydration, mapping, relations

Attachments: File DDC2383Test.php    

 Description   

I'm trying to accomplish something like this:
http://docs.doctrine-project.org/en/latest/tutorials/composite-primary-keys.html#use-case-2-simple-derived-identity

For two entities (Foo<>Bar) it works as expected but adding another entity related to Bar (so it's Foo<>Bar<>Baz) ends up with this error:

Fatal error: Uncaught exception 'Doctrine\ORM\Mapping\MappingException' with message 'The column id must be mapped to a field in class Entity\Bar since it is referenced by a join column of another class.' in C:\...\vendor\doctrine\orm\lib\Doctrine\ORM\Mapping\MappingException.php:203
Stack trace:
#0 C:\...\vendor\doctrine\orm\lib\Doctrine\ORM\Persisters\BasicEntityPersister.php(734): Doctrine\ORM\Mapping\MappingException::joinColumnMustPointToMappedField('Entity\Bar', 'id')
#1 C:\...\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php(2509): Doctrine\ORM\Persisters\BasicEntityPersister->loadOneToOneEntity(Array, Object(Entity\Bar))
#2 C:\...\vendor\doctrine\orm\lib\Doctrine\ORM\Internal\Hydration\ObjectHydrator.php(245): Doctrine\ORM\UnitOfWork->createEntity('Entity\Bar', Array, Array)
#3 C:\...\vendor\doctrine\orm\lib\Doctrine\ORM\Internal\Hydration\ObjectHydrator.php(424): Doctrine\ORM\Internal\Hydration\Ob in C:\...\vendor\doctrine\orm\lib\Doctrine\ORM\Mapping\MappingException.php on line 203

This error appears when there are some records in the database and I want to query for example all Foos.

My entites look like this:

//Entity/Foo.php

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

    /** @OneToOne(targetEntity="Bar", mappedBy="foo") */
    protected $bar;

    public function getId()
    {
        return $this->id;
    }

    public function getBar()
    {
        return $this->bar;
    }

    public function setBar($bar)
    {
        $bar->setFoo($this);
        $this->bar = $bar;
    }
}

//Entity/Bar.php

/** @Entity @Table(name="bars") */
class Bar
{
    /** @Id @OneToOne(targetEntity="Foo", inversedBy="bar")
     * @JoinColumn(name="id", referencedColumnName="id") */
    protected $foo;

    /** @OneToOne(targetEntity="Baz", mappedBy="bar") */
    protected $baz;

    public function __construct($foo)
    {
        $this->foo = $foo;
    }

    public function getId()
    {
        return $this->getFoo()->getId();
    }

    public function getFoo()
    {
        return $this->foo;
    }

    public function setFoo($foo)
    {
        $this->foo = $foo;
    }

    public function getBaz()
    {
        return $this->baz;
    }

    public function setBaz($baz)
    {
        $bar->setBar($this);
        $this->baz = $baz;
    }
}

//Entity/Baz.php

/** @Entity @Table(name="bazes") */
class Baz
{
    /** @Id @OneToOne(targetEntity="Bar", inversedBy="baz")
     * @JoinColumn(name="id", referencedColumnName="id") */
    protected $bar;

    public function __construct($bar)
    {
        $this->bar = $bar;
    }

    public function getId()
    {
        return $this->getBar()->getId();
    }

    public function getBar()
    {
        return $this->bar;
    }

    public function setBar($bar)
    {
        $this->bar = $bar;
    }
}

And fails on

$fooRepository = $em->getRepository('Entity\Foo');
$foos = $fooRepository->findAll();


 Comments   
Comment by Jacek Jędrzejewski [ 01/Apr/13 ]

Attaching a test case which results in two exceptions - while creating the schema and while fetching entities.

Comment by Benjamin Eberlei [ 14/Apr/13 ]

This is sadly a restriction of the foreign keys as primary key feature.

Due to the architecture of shared nothing Metadata instances we cannot validate this at mapping compile time, only at runtime, thus leading to this error.





[DDC-2370] Subclass annotations not being read, unable to use OneToMany relation with single table inheritance Created: 26/Mar/13  Updated: 01/May/13  Resolved: 01/May/13

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

Type: Bug Priority: Major
Reporter: Arthur Bodera Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: annotationdriver, inheritance, orm
Environment:

PHP 5.4.11



 Description   

Subclasses that override parent class properties and define relations will not work as expected, because AnnotationDriver/Reader will only use the parent class annotation (discarding whatever subclass defined).

The following code will produce error:

[Mapping]  FAIL - The entity-class 'Test\Office' mapping is invalid:
* The mappings Test\Office#employees and Employee#office are incosistent with each other.

Test code:

<?php
namespace Test;
 
use Doctrine\ORM\Mapping as ORM;
 
/**
 * @ORM\Entity
 */
class Office 
{
    /**
     * @ORM\OneToMany(targetEntity="Person", mappedBy="office")
     * @var Person[]|ArrayCollection
     */
    protected $people;
 
    /**
     * @ORM\OneToMany(targetEntity="Employee", mappedBy="office")
     * @var Employee[]|ArrayCollection
     */
    protected $employees;
 
}
 
/**
 * @ORM\Entity
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="type", type="string")
 * @ORM\DiscriminatorMap({"employee" = "Employee"})
 */
class Person
{
    /**
     * @ORM\ManyToOne(targetEntity="Office", inversedBy="people")
     * @var Office
     */
    protected $office;
}
 
/**
 * @ORM\Entity
 */
class Employee extends Person
{
    /**
     * @ORM\ManyToOne(targetEntity="Office", inversedBy="employees")
     * @var Office
     */
    protected $office;
}


 Comments   
Comment by Benjamin Eberlei [ 01/May/13 ]

Overwriting assocations in this way is not supported.

Comment by Arthur Bodera [ 01/May/13 ]

Ok, I get that it's not supported right now, but why did you mark it as resolved?





[DDC-2359] ClassMetadataFactory::wakeupReflection() is called twice Created: 20/Mar/13  Updated: 24/Mar/13  Resolved: 24/Mar/13

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers, ORM
Affects Version/s: Git Master, 2.3.2
Fix Version/s: 2.4

Type: Improvement Priority: Major
Reporter: Stefan Kleff Assignee: Marco Pivetta
Resolution: Fixed Votes: 0
Labels: None


 Description   

ClassMetadataFactory::wakeupReflection() is called in Common\...\AbstractClassMetadataFactory::loadMetadata() at the end of the method. A few lines after that ORM\...\ClassMetadatafactory::doLoadMeadata() is called, where wakeupReflection() was already called. I think this has been overlooked during the refactoring of the factories. I think the call in doLoadMetadata() is redundant..



 Comments   
Comment by Marco Pivetta [ 24/Mar/13 ]

Fix at DDC-2369 - https://github.com/doctrine/doctrine2/pull/630





[DDC-2324] mapOneToMany not working after upgrade to symfony2.1 Created: 28/Feb/13  Updated: 04/Mar/13  Resolved: 04/Mar/13

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

Type: Bug Priority: Major
Reporter: Thomas Mayer Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None
Environment:

debian 6, php 5.4.10



 Description   

After updating to from symfony 2.0 to symfony 2.1, creating a new mapping did not work when using \Doctrine\ORM\Mapping\ClassMetadata::mapOneToMany().

The code used was:

        /** @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */
        $metadata = $this->getDoctrine()->getEntityManager()->getClassMetadata('SecretSecretBundle:Deal');

        if (!array_key_exists('rolap', $metadata->getAssociationMappings())) {
            // use a temporary join mapping
            $metadata->mapOneToMany(array(
                'targetEntity' => 'Secret\SecretBundle\Entity\RolapDealP1m',
                'fieldName' => 'rolap',
                'mappedBy' => 'deal',
            ));
        }

A manyToOne mapping from RolapDealP1m to Deal was already created in the RolapDealP1m entity class.

Then, a query using the queryBuilder was created like this:

$qb=$repo->createQueryBuilder('Deal');
$qb
    ->join('Deal.rolap', 'Rolap')
[additional joins]
    ->select(
        array(
            'Deal.number number',
            'Deal.product productName',
[additional fields]
        )
    )
[additional where and group by]
;

The problem occurs, when doing a simple

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

On symfony 2.0 using doctrine 2.2.2 it worked fine, the result was returned.
On symfony 2.1 using doctrine 2.3.2 and 2.2.2 an error occurs:

Notice: Undefined index: rolap in /var/www/vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php line 366

As a workaround, we added the OneToMany mapping to the Deal Entity instead of using a temporary mapping. This worked fine with symfony 2.1/doctrine 2.3.2.

We think there has been a regression when trying to create temporary mappings.



 Comments   
Comment by Marco Pivetta [ 28/Feb/13 ]

Please validate the generated mappings with Doctrine\ORM\Tools\SchemaValidator.php

Comment by Thomas Mayer [ 28/Feb/13 ]

Using symfony 2.0 and doctrine 2.2.2, after the mapOneToMany() mapping SchemaValidator returns
'Secret\SecretBundle\Entity\Deal' =>
array (size=1)
0 => string 'The field Secret\SecretBundle\Entity\Deal#rolap is on the inverse side of a bi-directional relationship, but the specified mappedBy association on the target-entity Secret\SecretBundle\Entity\RolapDealP1m#deal does not contain the required 'inversedBy=rolap' attribute.' (length=271)

However, this works fine.

SchemaValidator returns the same when using symfony 2.1/doctrine 2.3.2, which is not working any more when doing the getResult()

Comment by Marco Pivetta [ 28/Feb/13 ]

Thomas Mayer are you able to write a failing test case for this one? It may just be an undocumented BC break though.

Comment by Thomas Mayer [ 28/Feb/13 ]

I will try to track it down to a smaller model for the test case.

Comment by Benjamin Eberlei [ 04/Mar/13 ]

Changing the mapping of entities after loading from a driver is undefined behavior.





[DDC-2309] Invalid behaviour to flush only one entity Created: 21/Feb/13  Updated: 01/May/13  Resolved: 01/May/13

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.2, 2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Martin Hasoň Assignee: Benjamin Eberlei
Resolution: Duplicate Votes: 0
Labels: None

Issue Links:
Duplicate
duplicates DDC-2267 EntityManager throws an exception whe... Resolved

 Description   

Current implementation of $em->flush($entity):

  • does not flush entity scheduled for delete
  • flush all entities scheduled for insert

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



 Comments   
Comment by Benjamin Eberlei [ 14/Mar/13 ]

The second point is documented, the first point i don't understand, can you elaborate?

Comment by Benjamin Eberlei [ 01/May/13 ]

Duplicate of DDC-2267





[DDC-2245] EntityManager#getReference returns NULL on SINGLE_TABLE inheritance Created: 15/Jan/13  Updated: 20/Jan/13  Resolved: 20/Jan/13

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

Type: Bug Priority: Major
Reporter: Masaki Fujimoto Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None


 Description   

When EntityManager#getReference is called with SINGLE_TABLE inherited entity, it tries to get a loaded entity by calling unitOfWork->tryGetById($sortedId, $class->rootEntityName). The call may return an entity object of root entity class which is not what is asked, then it ends up returning NULL instead of going further.



 Comments   
Comment by Marco Pivetta [ 15/Jan/13 ]

This looks quite serious. On the other side, `getReference` should probably call `find` on inheritances.

Do you have any example code for this?

Comment by Masaki Fujimoto [ 15/Jan/13 ]

Yes, following line returns NULL with entity classes I have(it's a part of Symfony2 project):

$entity = $em->getRepository('EnjoitechBaseBundle:MCode')->find('01') // load an entity of root entity class
$ref = $em->getReference('Enjoitech\BaseBundle\Entity\MCodeModule', '01'); // try to get reference of sub entity with same ID, this return NULL

// $ref => NULL


// MCode.php
<?php

namespace Enjoitech\BaseBundle\Entity;

use \PDO;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="M_CODE")
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="CLASS", type="string", length=2)
 * @ORM\DiscriminatorMap({"00" = "MCode", "01" = "MCodeModule"})
 */
class MCode
{
    /**
     * @ORM\Id
     * @ORM\Column(type="string", length=2)
     */
    protected $CODE;

    /**
     * @ORM\Column(type="string", length=128)
     */
    protected $DESCRIPTION;

    public function getCODE()
    {
        return $this->CODE;
    }
}


/**
 * @ORM\Entity
 */
class MCodeModule extends MCode
{
}

I also saw a post that mentioned a similar/same issue at https://groups.google.com/forum/#!msg/doctrine-user/55IkFJlADh8/79QpCIH1Ag4J

Comment by Benjamin Eberlei [ 20/Jan/13 ]

This is the correct behavior, if you fetch MCodeModule and its "only" a MCode, then returning null is correct, because you assume to retrieve a MCodeModule or nothing.

Comment by Masaki Fujimoto [ 20/Jan/13 ]

I am not assuming getReference is supposed to fetch/retrieve/load anything. Shouldn't it return a reference to an entity object even the target entity hasn't been loaded yet? getReference won't return null because you'll never know if the entity exists in database in my opinion.

Comment by Marco Pivetta [ 20/Jan/13 ]

Masaki Fujimoto that doesn't work with inheritances, since you will need to query the discriminator column to know what object to instantiate

Comment by Masaki Fujimoto [ 20/Jan/13 ]

I see, thanks for clarifying that. That was what I thought as far as I see in code; $sortedId array doesn't include discriminator column and value at all. So basically getReference won't guarantee its behaviour when the target is inheritances correct? I should rather use find() maybe. Will you keep that policy for future?

I also encountered few more issues related to SINGLE_TABLE inheritance. something like find() returns entities of other inheritance class that were loaded earlier. I needed to clear entityManager each time before I get entities of another subclassed of MCode. I guess there may be same sort of implementation without considering discriminator column. Are these all known issues or it's just how it is intended?

Comment by Marco Pivetta [ 20/Jan/13 ]

Masaki Fujimoto repeated calls to `find` give you the same instances for same identifiers. If you changed something, you'll need to `clear`, though it looks like you're doing a lot of unconventional stuff in there.

I think that on STI/JTI, `getReference` could short-circuit to `find`, not sure if we want it.

Comment by Masaki Fujimoto [ 20/Jan/13 ]

I have just one code table. PK is a combination of CLASS and CODE columns. I use CLASS column as discriminator, and CODE column is ID of each inheritance. value in CODE column won't be unique by itself in the table but I thought SINGLE_TABLE inheritance can cover that. If this structure is unconventional, I'll have to look for workaround. thanks for all your help





[DDC-2238] doctrine:schema:update partially broken Created: 11/Jan/13  Updated: 01/May/13  Resolved: 01/May/13

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Tools
Affects Version/s: 2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Tom Vogt Assignee: Benjamin Eberlei
Resolution: Duplicate Votes: 0
Labels: postgresql, schematool
Environment:

OS X 10.7.5
PHP 5.4.4
Postgres SQL 9.1.6

also confirmed on:
Linux (Debian testing, Kernel 2.6.32)
PHP 5.4.4
PostgreSQL 9.1.9
Doctrine 2.3.2


Attachments: Text File schemadiff.txt    
Issue Links:
Duplicate
duplicates DBAL-504 DBAL Enum fields migration issue / Po... Resolved

 Description   

the app/console doctrine:schema:update command generates a seemingly random number of statements like these:

ALTER TABLE geodata ALTER humidity SET ;
ALTER TABLE geodata ALTER lake SET ;
ALTER TABLE message ALTER translate SET ;

which are obvious invalid SQL commands. The mappings are fine, validate and the application works just fine. Here's an example from the mapping files including two of the above statements:

<field name="coast" type="boolean"/>
<field name="lake" type="boolean"/>
<field name="river" type="boolean"/>
<field name="humidity" type="float"/>
<field name="biome" type="string"/>

I am using doctrine2-spatial as an extension for GIS information. This problem shows up both in entities using spatial data and entities not using spatial data.

I'll gladly help debug this, as right now I can't update my dev database with --force, I need to use --dump-sql and filter out the invalid lines.



 Comments   
Comment by Benjamin Eberlei [ 12/Jan/13 ]

Can you dump the SchemaDiff/ColumnDiff instances that are returned from lib/Doctrine/DBAL/Schema/Comparator.php?

Comment by Tom Vogt [ 12/Jan/13 ]

requested dump of SchemaDiff

Comment by Tom Vogt [ 12/Jan/13 ]

added in the file schemadiff.txt - I added this in Schematool.php - getUpdateSchemaSql():

$comparator = new Comparator();
$schemaDiff = $comparator->compare($fromSchema, $toSchema);
\Doctrine\Common\Util\Debug::dump($schemaDiff, 6);

if you need other output, just tell me what entity to dump and where. I'll be happy to help.

The file also contains the buggy update statements it creates towards the end. There's a few non-crucial bugs included, where it alters the geospatial columns to themselves (i.e. river.course already is a geometry/linestring). I don't worry about those because they don't break anything.

Comment by Tom Vogt [ 15/Apr/13 ]

Is there any update on this? I'm still having this issue, with many different entities, always the same problem, for example:

ALTER TABLE event ALTER priority SET ;

Which is an integer field on an entity that doesn't have any GIS elements, so I'm not even sure if it's caused by that anymore.

Comment by Benjamin Eberlei [ 01/May/13 ]

Tom Vogt I added a fix for PostgreSQL today, can you verify again if this works? Its included in the 2.3 branch.

Comment by Benjamin Eberlei [ 01/May/13 ]

Duplicate of http://www.doctrine-project.org/jira/browse/DBAL-504





[DDC-2210] PHP warning in ProxyFactory when renaming proxy file Created: 20/Dec/12  Updated: 13/Oct/14  Resolved: 13/Oct/14

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

Type: Improvement Priority: Major
Reporter: Matthieu Napoli Assignee: Marco Pivetta
Resolution: Fixed Votes: 0
Labels: None
Environment:

Windows


Issue Links:
Reference
relates to DCOM-186 [GH-269] ProxyGenerator eval() proxy ... Resolved
relates to DCOM-209 [GH-291] [DDC-717] Add eval() and FIL... Resolved
relates to DDC-717 Do not use files when using proxy aut... Resolved

 Description   

Getting a PHP Warning:

rename(**/models/Proxies_CGAF_Model_Component_Group.php.50d2dd2c079bb9.35271255,**/models/Proxies__CG_AF_Model_Component_Group.php):

in ProxyFactory line 194.

I haven't more information in the warning.

This is the moment when the ProxyFactory writes the proxy to a temporary file and then tries to rename the temp file to the correct file.

This warning appears randomly, but mostly on pages with lots of concurrent AJAX requests. I guess this happens because several requests try to write the proxy file at the same time. I get this warning but the app works fine.

This happens in dev environment, on a Windows machine.

I don't know why rename generates a warning, it should just return false... The doc doesn't say anything about warnings (except for long file names, but I checked even with the full path this is around 135 characters, not 255).



 Comments   
Comment by Benjamin Eberlei [ 22/Dec/12 ]

Thats why you shouldn't generate proxies at runtime. The problem happens on windows, because the atomic rename operation doesn't work as perfectly there as on linux.

We cannot fix this in Doctrine.

Comment by Matthieu Napoli [ 24/Dec/12 ]

Benjamin Eberlei What do you mean "you shouldn't generate proxies at runtime"? I'm not in production, this is in dev. And I'm using the default configuration.

What I don't understand is why will Doctrine regenerate proxies on every request? The warning is reproductible, and even when no PHP entity has been touched.

Comment by Matthieu Napoli [ 27/Dec/12 ]

Benjamin Eberlei To simplify my previous message (I don't want to bury you under questions) I'll sum it up like that:

What can I do?

Thanks!

Comment by Matthieu Napoli [ 28/Feb/13 ]

Benjamin Eberlei ping: what can be done?

Can we suppress the error with @rename($tmpFileName, $fileName); ?

https://github.com/doctrine/common/blob/master/lib/Doctrine/Common/Proxy/ProxyGenerator.php#L287

I can make a PR if you think that's a valid solution.

Comment by Marco Pivetta [ 28/Feb/13 ]

Matthieu Napoli no, if you have warnings, please disable them via ini setting. With error suppression there, we may have further problems identifying more serious issues.

About proxy generation: that happens EVERY time in dev environments. Generate them once and disable it afterwards.

Comment by Matthieu Napoli [ 28/Feb/13 ]

Marco Pivetta OK I can disable the auto generation then (I'll have to remember to regenerate them when I edit the model).

Thanks for the feedback

Is that possible to make those proxies generate only if the entity file has been modified since the last generation? (only asking if can and should be done, I can look for implementing it myself if that's the case)

Comment by Marco Pivetta [ 28/Feb/13 ]

Matthieu Napoli that would be very obnoxious when changing entities often. I wouldn't do that (generating only if not already available)

Comment by Matthieu Napoli [ 28/Feb/13 ]

Marco Pivetta Yes but for now they are regenerated at every request when in dev mode (at least with the default configuration http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/configuration.html#obtaining-an-entitymanager)

Which one is worse: generating every proxy class at every request, or generate only those which changed (in dev environment of course, not prod)?

If neither of these options are good (i.e. auto generation should be disabled), I don't understand why the docs say to enable auto generation when in dev environment.

Comment by Marco Pivetta [ 28/Feb/13 ]

Matthieu Napoli that's because in dev environments you shouldn't care about that one exception (usually happens when you got concurrent requests).

It is worse to generate only on changes: that's a lot of additional checks, variables to keep in memory and additional logic that is not needed.

Let's keep it as it is (generating at each request) for dev environments: works fine

Another (eventual) solution for dev environments would be not to write the proxy file, but to eval it.

Comment by Matthieu Napoli [ 28/Feb/13 ]

eval it would be a good solution IMO, no more "woops the directory is not writable" and it's more neutral for the user filesystem (but not as easy to debug). But OK, I see what you mean, it works let's keep it that way.

Actually the problem on my setup is that PHP errors are turned into exceptions, so on an (poorly designed) AJAX treeview (lots of nodes to load => lots of requests), I end up with some nodes not loaded because of the exception. And it feels weird to either silently log all PHP warnings or silently ignore the specific warning for the rename.

Comment by Marco Pivetta [ 28/Feb/13 ]

Matthieu Napoli I'd go with `eval` then. Needs refactoring of the abstract proxy factory and of the proxy generator (proxy generator should no longer write files).

Comment by Marco Pivetta [ 28/Feb/13 ]

Re-opening: the proxy factory could directly `eval()` the produced proxy code. The ProxyGenerator should no longer write the generated files to disk automatically.

Comment by Matthieu Napoli [ 28/Mar/13 ]

I've opened a PR: https://github.com/doctrine/common/pull/269

Comment by Oleg Namaka [ 16/Aug/13 ]

Thats why you shouldn't generate proxies at runtime. The problem happens on windows, because the atomic rename operation doesn't work as perfectly there as on linux.

  • In my case that is observed on a Linux machine (see http://www.doctrine-project.org/jira/browse/DDC-2613). If the rename operation is atomic then why it still happens? As I indicated in the description it's because of the way uniqid function works.
  • Is there a plan to merge the PR in this ticket? The fix in it would eliminate my issue whatsoever.
Comment by Doctrine Bot [ 20/Aug/13 ]

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

Comment by Marco Pivetta [ 13/Oct/14 ]

This issue does not need a resolution anymore, as we allow using eval() as proxy generation strategy in 2.5.





[DDC-2196] EntityManager can't be extended easily Created: 14/Dec/12  Updated: 16/Dec/12  Resolved: 16/Dec/12

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

Type: Bug Priority: Major
Reporter: Matthieu Napoli Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None


 Description   
public static function create($conn, Configuration $config, EventManager $eventManager = null)
{
    // ...
    return new EntityManager($conn, $config, $conn->getEventManager());
}

The EntityManager::create method uses new on the EntityManager class instead of static.

This makes extending that class not practical because we have to rewrite (duplicate) EntityManager::create.

Code could be extendable with:

public static function create($conn, Configuration $config, EventManager $eventManager = null)
{
    // ...
    return new static($conn, $config, $conn->getEventManager());
}


 Comments   
Comment by Matthieu Napoli [ 14/Dec/12 ]

Pull request is here: https://github.com/doctrine/doctrine2/pull/535

Comment by Benjamin Eberlei [ 16/Dec/12 ]

Its not desired to override the EntityManager, we are currently building a PR to build a decorator for the EntityManager instead. You can decorate the EntityManager yourself.

Comment by Matthieu Napoli [ 16/Dec/12 ]

Benjamin Eberlei Shouldn't it be final then?





[DDC-2191] Bug in QueryBuilder::add() method, param $append has no effect for where/having DQL parts Created: 07/Dec/12  Updated: 08/Sep/13  Resolved: 06/Jan/13

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: Git Master
Fix Version/s: 2.4

Type: Bug Priority: Major
Reporter: Mykola Zyk Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: None


 Description   

Now $append param of QueryBuilder::add() method has no effect for where and having parts.

In example:

$query->add('where', 'u.some = ?1');
$query->add('where', 'u.other = ?2', true);

will result in the loss of condition u.some = ?1

Explanation in code
526 line of Doctrine/ORM/QueryBuilder.php, part of body add() method:

if ($append && $isMultiple) {
    if (is_array($dqlPart)) {
        $key = key($dqlPart);
        $this->_dqlParts[$dqlPartName][$key][] = $dqlPart[$key];
    } else {
        $this->_dqlParts[$dqlPartName][] = $dqlPart;
    }
} else {
    $this->_dqlParts[$dqlPartName] = ($isMultiple) ? array($dqlPart) : $dqlPart;
}

According to the code above $append parameter is checked in conjunction with $isMultiple variable, which is:

$isMultiple = is_array($this->_dqlParts[$dqlPartName]);

But in 56 line of this file, class property _dqlParts keys where and having are equal null:

private $_dqlParts = array(
    'distinct' => false,
    'select'  => array(),
    'from'    => array(),
    'join'    => array(),
    'set'     => array(),
    'where'   => null,
    'groupBy' => array(),
    'having'  => null,
    'orderBy' => array()
);

As a result, for the parts where and having condition $append && $isMultiple will never be true, regardless of $append value.

I can offer a patch on Github to fix this bug, if necessary.



 Comments   
Comment by Benjamin Eberlei [ 06/Jan/13 ]

This was and will never be allowed, i introduced an exception to show a way out, you need to look at QueryBuilder#andWhere for example to see a solution to append to where clauses.





[DDC-2186] PreFlushEventArgs not passed by ClassMetadataInfo::invokeLifecycleCallbacks() Created: 05/Dec/12  Updated: 02/Feb/13  Resolved: 02/Feb/13

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers
Affects Version/s: 2.3
Fix Version/s: 2.4

Type: Improvement Priority: Major
Reporter: Kevin Herrera Assignee: Fabio B. Silva
Resolution: Fixed Votes: 0
Labels: None


 Description   

As described in the documentation (http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#preflush) my pre-flush lifecycle callback is not receiving an instance of Doctrine\ORM\Event\PreFlushEventArgs when called in Doctrine\ORM\Mapping\ClassMetadataInfo::invokeLifecycleCallbacks().



 Comments   
Comment by Fabio B. Silva [ 05/Dec/12 ]

Hi Kevin,
The current lifecycle event system does not allow access to the event args. :
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#lifecycle-callbacks.

Now it is possible just by using the EventManager :
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#listening-to-lifecycle-events

Just after DDC-1955 : (https://github.com/doctrine/doctrine2/pull/423) be merged it will be possible.

Cheers

Comment by Fabio B. Silva [ 13/Dec/12 ]

Change issue type, since it's not a bug.

Comment by Fabio B. Silva [ 02/Feb/13 ]

fixed : https://github.com/doctrine/doctrine2/commit/71a68a5c6fcd49538c3ef2f86d64bcde1958251c





[DDC-2148] Many-to-many not working with interface Created: 16/Nov/12  Updated: 22/Nov/12  Resolved: 22/Nov/12

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: DQL
Affects Version/s: 2.3
Fix Version/s: 2.2

Type: Bug Priority: Major
Reporter: Moritz Kraft Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: dql
Environment:

Linux, PHP 5.3.10, Symfony 2.2



 Description   

First off, here's a pastie with all the code and mappings involved, and a stacktrace: http://pastie.org/5372087

Not sure if this a bug or not, but I think that according to the docs this should work - in a vendor bundle I have an entity defining a unidirectional many-to-many relation to an interface: the entity is Group and defines a many-to-many relation to a UserInterface, which is resolved correctly in the app configuration (as the many-to-one relations using it in the other entities of this vendor bundle work fine).

I'm going by these docs:

http://symfony.com/doc/master/cookbook/doctrine/resolve_target_entity.html

However, when adding a user to a group, I'm getting a weird error:

An exception occurred while executing 'INSERT INTO acme_group_user (group_id, user_id) VALUES (?, ?)' with params

{"1":2,"2":1,"3":2,"4":1}

:

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

For some reason it's adding 4 parameters to the statement instead of 2.

Oddly enough, the query generation works perfectly fine when I replace the interface in the mapping with the actual final entity. But that wasn't the point of the exercise... I need to use the interface there.

Also, in other entities in that GroupBundle which are referencing the UserInterface using a different relation type, i.e. many-to-one, the relations work perfectly fine.

The schema validates as well, using doctrine:schema:validate in the console.



 Comments   
Comment by Marco Pivetta [ 16/Nov/12 ]

"many-to-many TO a mapped superclass"? I don't think relations TO mapped superclasses are supported in any way... A mapped superclass should never appear in a `targetEntity` mapping.

Could you please re-formulate the description of the issue? There is no mapped superclass in your examples

Comment by Moritz Kraft [ 16/Nov/12 ]

You are of course right. Edited the issue description/title.

It is a blocker for us, btw., not minor - being able to use a many-to-many relation there is rather central to the code of our app. I'm not seeing a workaround, easy or otherwise.

Comment by Marco Pivetta [ 16/Nov/12 ]

Moritz Kraft yes, but it is not a blocker for the next release Will restore prio.

Comment by Moritz Kraft [ 16/Nov/12 ]

Ah right, yeah, that makes sense. Thank you!

Comment by Moritz Kraft [ 22/Nov/12 ]

Fixed in 1b5f051 - thanks Benjamin!

Comment by Moritz Kraft [ 22/Nov/12 ]

Fixed in 2.3 branch, backported to 2.2 as well





[DDC-2144] PersistentCollection Criteria IS NULL not behaving as expected Created: 14/Nov/12  Updated: 14/Nov/12  Resolved: 14/Nov/12

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.3
Fix Version/s: 2.3.1

Type: Bug Priority: Major
Reporter: Aitor Suso Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None


 Description   

When using the matching method of a persistentCollection with a Criteria that contains a call to isNull, the SQL generated contains "field = null" instead of "field IS null"



 Comments   
Comment by Aitor Suso [ 14/Nov/12 ]

Seen that the code is fixed in the 2.3 branch, but it isn't in the last stable release (2.3.0)





[DDC-2052] Custom tree walkers are not allowed to add new components to the query Created: 02/Oct/12  Updated: 08/Feb/14  Resolved: 08/Feb/14

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: DQL
Affects Version/s: 2.3
Fix Version/s: 2.5

Type: Improvement Priority: Major
Reporter: Łukasz Cybula Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 2
Labels: dql


 Description   

Custom tree walkers have freedom in modifying the AST but when you try to add a new query component (i.e. new join in walkSelectStatement() ) to the AST then the SqlWalker throws an exception because it does not has the new component in its _queryComponents array. I see two possible ways to resolve this:
1. Modify the Parser class in order to allow tree walkers to modify queryComponents and pass changed queryComponents to the SqlWalker
2. Improve SqlWalker so it can extract and prepare needed information about queryComponent based on AST when it does not have them.



 Comments   
Comment by Benjamin Eberlei [ 06/Oct/12 ]

Ok this is much more complicated to allow then i thought. The problem is that the QueryComponents are passed by value, as an array, not by reference. That prevents changing them because this change wouldn't be visible in the output walker.

I can add a method to allow this in the OutputWalker for now, but generally this requires a bigger refactoring on the Query Components.

Comment by Benjamin Eberlei [ 06/Oct/12 ]

Added setQueryComponent() in SQL Walker to allow modification in output walker.

Comment by Łukasz Cybula [ 08/Oct/12 ]

I'm afraid that this doesn't solve the initial problem at all. I'll try to describe it in more details to show what I mean. Suppose we have two doctrine extensions each of which contain its own tree walker. Each of these tree walkers need to modify AST and add new component to it (joined with some component already existing in the query). The first problem is that each tree walker has its own queryComponents array which is not passed between them, although they not necessary need to use queryComponents - they could use only AST. The second, bigger problem is that the Parser class does not know anything about modifications of queryComponents in tree walkers and cannot pass modified version to the OutputWalker. The goal of submitting this issue was to allow adding new components to the query in tree walkers which is not achievable by your fix. I think it may be the first step in the right direction. Maybe TreeWalkerAdapter should have public method getQueryComponents() which would be used by the Parser to pass modified queryComponents between different tree walkers and finally to the OutputWalker ? This would not break backward compatibility and solve this issue. What do you think about it?

Comment by Łukasz Cybula [ 08/Oct/12 ]

I've tried to implement the solution mentioned in previous comment but it's also not so clean and easy as I thought. Each tree walker (including TreeWalkerChain) would have to implement getQueryComponents() and setQueryComponent($alias, array $component) methods. The same with SqlWalker, so the TreeWalker interface should have these methods, which would break BC in some way (walkers that do not inherit from SqlWalker or TreeWalkerAdapter will fail to compile). So maybe my first solution (PR #464) is not so bad for now? In the future queryComponents could be replaced by a special object or could be passed by a reference to allow modifications.

Comment by Benjamin Eberlei [ 09/May/13 ]

Marked as improvement as its not a bug.

A solution might probably implement an object holding all the QueryComponent, implementing ArrayAccess. So that way the state can be shared.

Comment by Marco Pivetta [ 14/May/13 ]

Just hit this while developing an ast walker... Will look into it too since I need it more than soon.

Comment by Marco Pivetta [ 14/May/13 ]

As a VERY UGLY workaround, I used a static variable and a custom sql walker in combination with my AST walker.

namespace Comcom\Versioning\ORM\Query;


use Doctrine\ORM\Query\SqlWalker;

class WorkaroundSqlWalker extends SqlWalker
{
    public function __construct($query, $parserResult, array $queryComponents)
    {
        parent::__construct($query, $parserResult, $queryComponents);

        foreach (VersionWalker::$additionalAliases as $alias => $value) {
            $this->setQueryComponent($alias, $value);
        }
    }
}
Comment by Andreas H [ 21/Jan/14 ]

My workaround is to overwrite the TreeWalkerChain class (using Composer) and pulling the query components from the last iteration in walkSelectStatement to the next one.

Comment by Benjamin Eberlei [ 08/Feb/14 ]

Partial fix in https://github.com/doctrine/doctrine2/pull/934





[DDC-2023] IDENTITY() in subquery throws error Created: 11/Sep/12  Updated: 14/Apr/13  Resolved: 14/Apr/13

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: DQL
Affects Version/s: 2.2
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Adrien Brault Assignee: Benjamin Eberlei
Resolution: Duplicate Votes: 0
Labels: None


 Description   

Hi, the following query

public function testIdentityFunctionInSubqueryClause()
{
    $sql = $this->_em->createQuery(
        "SELECT a
         FROM Doctrine\Tests\Models\CMS\CmsAddress a
         WHERE a.user IN (
             SELECT IDENTITY(a2.user)
             FROM Doctrine\Tests\Models\CMS\CmsArticle a2
         )"
    )->getSql();
}

throws an error:

1) Doctrine\Tests\ORM\Query\SelectSqlGenerationTest::testIdentityFunctionInSubqueryClause
Doctrine\ORM\Query\QueryException: [Syntax Error] line 0, col 85: Error: Expected Doctrine\ORM\Query\Lexer::T_FROM, got '('

/Users/adrienbrault/Developer/php/mygithub/doctrine2/lib/Doctrine/ORM/Query/QueryException.php:42
/Users/adrienbrault/Developer/php/mygithub/doctrine2/lib/Doctrine/ORM/Query/Parser.php:380
/Users/adrienbrault/Developer/php/mygithub/doctrine2/lib/Doctrine/ORM/Query/Parser.php:255
/Users/adrienbrault/Developer/php/mygithub/doctrine2/lib/Doctrine/ORM/Query/Parser.php:1189
/Users/adrienbrault/Developer/php/mygithub/doctrine2/lib/Doctrine/ORM/Query/Parser.php:1280
/Users/adrienbrault/Developer/php/mygithub/doctrine2/lib/Doctrine/ORM/Query/Parser.php:2737
/Users/adrienbrault/Developer/php/mygithub/doctrine2/lib/Doctrine/ORM/Query/Parser.php:2228
/Users/adrienbrault/Developer/php/mygithub/doctrine2/lib/Doctrine/ORM/Query/Parser.php:2145
/Users/adrienbrault/Developer/php/mygithub/doctrine2/lib/Doctrine/ORM/Query/Parser.php:2121
/Users/adrienbrault/Developer/php/mygithub/doctrine2/lib/Doctrine/ORM/Query/Parser.php:2089
/Users/adrienbrault/Developer/php/mygithub/doctrine2/lib/Doctrine/ORM/Query/Parser.php:2064
/Users/adrienbrault/Developer/php/mygithub/doctrine2/lib/Doctrine/ORM/Query/Parser.php:1212
/Users/adrienbrault/Developer/php/mygithub/doctrine2/lib/Doctrine/ORM/Query/Parser.php:760
/Users/adrienbrault/Developer/php/mygithub/doctrine2/lib/Doctrine/ORM/Query/Parser.php:727
/Users/adrienbrault/Developer/php/mygithub/doctrine2/lib/Doctrine/ORM/Query/Parser.php:213
/Users/adrienbrault/Developer/php/mygithub/doctrine2/lib/Doctrine/ORM/Query/Parser.php:288
/Users/adrienbrault/Developer/php/mygithub/doctrine2/lib/Doctrine/ORM/Query.php:231
/Users/adrienbrault/Developer/php/mygithub/doctrine2/lib/Doctrine/ORM/Query.php:177
/Users/adrienbrault/Developer/php/mygithub/doctrine2/tests/Doctrine/Tests/ORM/Query/SelectSqlGenerationTest.php:1375

I think that it's a bug and not a feature, because i tried to reproduce the last example from there http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#dql-select-examples



 Comments   
Comment by Alexander [ 11/Sep/12 ]

This is related to http://www.doctrine-project.org/jira/browse/DDC-1557. It seems the fix was not backported to 2.2.

Comment by Marco Pivetta [ 23/Jan/13 ]

Adrien Brault does it work for you in 2.3?

Comment by Benjamin Eberlei [ 14/Apr/13 ]

Duplicate of DDC-1557





[DDC-2006] one2many to self inverts table aliasses and creates wrong db query Created: 31/Aug/12  Updated: 04/May/13  Resolved: 04/May/13

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

Type: Bug Priority: Major
Reporter: Xavier Dekeyster Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None
Environment:

Debian VM, MySQL, Zend-Framework


Attachments: PNG File Screen Shot 2012-08-31 at 14.31.21.png    

 Description   

See attachment for description.



 Comments   
Comment by Fabio B. Silva [ 06/Apr/13 ]

Hi Xavier,

Could you past your entities and mappings please ?

Thanks

Comment by Benjamin Eberlei [ 14/Apr/13 ]

What version of Doctrine are you using? This sounds like a bug that was fixed some time ago

Comment by Benjamin Eberlei [ 04/May/13 ]

The query is correct, "c.parentCategory c2" generates the right query as per your screenshot. Its just not the order of the queries that you want, Native SQL wil help you here.





[DDC-1942] problem with serialize/merging entities with aggregation Created: 24/Jul/12  Updated: 16/Jan/15  Resolved: 27/Feb/13

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

Type: Bug Priority: Major
Reporter: gabriel sancho Assignee: Marco Pivetta
Resolution: Duplicate Votes: 3
Labels: merge, serialize
Environment:

linux, php 5.4.4, apache 2.2.22, mysql 5.5


Attachments: Text File project_debug.log    

 Description   

i have these two entities:

namespace nuevo_paquete;

class Clase_01{
	/**
	* @Id
	* @Column(name="id",type="integer",nullable=false)
	* @GeneratedValue
	*/
	protected $id;
        
        /**
	* @ManyToOne(targetEntity="\paquete_02\Clase_03", inversedBy="clase_01", fetch="EXTRA_LAZY", cascade={"detach","merge"})
	* @JoinColumn(name="clase_03", referencedColumnName="id")
	*/
	protected $clase_03;

        /**
	* @ManyToOne(targetEntity="\paquete_02\Clase_03", inversedBy="clase_01_1", fetch="EXTRA_LAZY", cascade={"detach","merge"})
	* @JoinColumn(name="clase_03_1", referencedColumnName="id")
	*/
	protected $clase_03_1;
}
namespace paquete_02;
class Clase_03{
   /**
	* @Id
	* @Column(name="id",type="integer",nullable=false)
	* @GeneratedValue
	*/
	protected $id;

        /**
	* @OneToMany(targetEntity="\nuevo_paquete\Clase_01", mappedBy="clase_03", fetch="EXTRA_LAZY", cascade={"detach"})
	*/
	protected $clase_01;
	
	/**
	* @OneToMany(targetEntity="\nuevo_paquete\Clase_01", mappedBy="clase_03_1", fetch="EXTRA_LAZY", cascade={"detach"})
	*/
	protected $clase_01_1;
}

Clase_01 have two aggregation association with Clase_03

Clase_01 ------> Clase_03

-----> Clase_03_1

when serialize an object of class Clase_01 and then unserialize, i lost the reference to the object of class Clase_03
but i can see Clase_03_1

ej:

$aux_orm = $em->find('nuevo_paquete\Clase_01', 1);
$em->detach($aux_orm);
$aux_s = serialize($aux_orm);
$aux_orm = unserialize($aux_s);

$aux_orm = $em->merge($aux_orm);
echo '['.$aux_orm->getId().']'; // [1]
echo '['.$aux_orm->getClase_03()->getId().']'; // [] expected : [1]
echo '['.$aux_orm->getClase_03_1()->getId().']'; // [1]

when i call get_clase_03() before detach the object, i can see the object Clase_03
ej:

$aux_orm = $em->find('nuevo_paquete\Clase_01', 1);
$aux_orm->getClase_03()->getId();

$em->detach($aux_orm);
$aux_s = serialize($aux_orm);
$aux_orm = unserialize($aux_s);

$aux_orm = $em->merge($aux_orm);
echo '['.$aux_orm->getId().']'; // [1]
echo '['.$aux_orm->getClase_03()->getId().']'; // [1]
echo '['.$aux_orm->getClase_03_1()->getId().']'; // [1]


 Comments   
Comment by gabriel sancho [ 24/Jul/12 ]

if i call $em->find() i still not able to view the object

//----------------------------------------
$aux_orm = $em->find('nuevo_paquete\Clase_01', 1);
$em->detach($aux_orm);
$aux_s = serialize($aux_orm);
$aux_orm = unserialize($aux_s);

$aux_orm = $em->merge($aux_orm);
echo '['.$aux_orm->getId().']'; // [1]
echo '['.$aux_orm->getClase_03()->getId().']'; // [] expected : [1]
echo '['.$aux_orm->getClase_03_1()->getId().']'; // [1]

$aux_orm = $em->find('nuevo_paquete\Clase_01', 1);
echo '['.$aux_orm->getId().']'; // [1]
echo '['.$aux_orm->getClase_03()->getId().']'; // still empty [] expected : [1]

//----------------------------------------
and if i have another register referencing the same object of class_03, i can't view
ej:

$aux_orm = $em->find('nuevo_paquete\Clase_01', 2);
echo '['.$aux_orm->getId().']'; // [2]
echo '['.$aux_orm->getClase_03()->getId().']'; // still empty [] expected : [1]
Comment by Marquez Alejandra [ 24/Jul/12 ]

i have the same problem

Comment by Benjamin Eberlei [ 29/Jul/12 ]

formatted code

Comment by Benjamin Eberlei [ 29/Jul/12 ]

Can you paste a var_dump() of class1 after you call detach and before serialize and then another one after you called unserialize? Also a var_dump of the serialized string $aux_s

Comment by gabriel sancho [ 30/Jul/12 ]

var_dump in attached file

Comment by gabriel sancho [ 11/Sep/12 ]

i found that if the class has more than two levels have the same problem
by ex. i have to do

// class1 -> register id 1
// class2 -> register id 1
// class3 -> null, don't exist
$class2 = $class1->getClass2();
$class3 = $class2->getClass3();
$class3->getId();

otherwise doctrine insert new registers in database for class3
after unserialize

Comment by gonzalo [ 11/Sep/12 ]

I have same problems

Comment by gabriel sancho [ 11/Sep/12 ]

if i declare in the entity annotation fetch="EAGER" works fine

Comment by Valentin Claras [ 11/Dec/12 ]

I have the same problem.

From what I saw, if I use fetch: EAGER, all my distinct entities are merged indeed, but if a specific entity (instance) is in two different collections, only one collection will have this instance.

So, any news about this bug ?

Comment by Valentin Claras [ 13/Dec/12 ]

I'm still trying to get my stuff works, and I'm now pretty sure that as soon as an object have to be merge more than once in a row (because of cascade associations), it end up being only in one collection, and lost for other entities.

I hope this could help.

Comment by Marco Pivetta [ 23/Jan/13 ]

I think this one is also related with DDC-1734 (noticed a lot of un-initialized objects).

gabriel sancho can you please try initializing ALL of these related objects prior to detaching/serializing and repeat your checks?

Comment by gabriel sancho [ 24/Jan/13 ]

How do I have to initialize the objects?

Comment by Marco Pivetta [ 24/Jan/13 ]

gabriel sancho by calling any method that is not `getId` on them.
This will initialize them

Comment by Marco Pivetta [ 23/Feb/13 ]

gabriel sancho news on this one? Managed to verify it?

Comment by Marco Pivetta [ 23/Feb/13 ]

This may be a duplicate of DDC-2306

Comment by Benjamin Eberlei [ 26/Feb/13 ]

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

Comment by Marco Pivetta [ 27/Feb/13 ]

This issue is valid only before the fix introduced at DDC-2306. Duplicate confirmed

Comment by Doctrine Bot [ 29/Apr/14 ]

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

Comment by Doctrine Bot [ 12/Nov/14 ]

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

Comment by Doctrine Bot [ 16/Jan/15 ]

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





[DDC-1932] Wrong generated SQL through EntityManager::createQuery($dql) Created: 17/Jul/12  Updated: 20/Jul/12  Resolved: 20/Jul/12

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

Type: Bug Priority: Major
Reporter: Osain J. Fdez. Rguez. Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: None
Environment:

Microsoft Windows 7 Ultimate, PHP v5.3.10 running under Apache Server.
Doctrine 2.1.7 included in Symfony 2.0.14 vendors
MSSQL Server 2008, Native Client 10.0, pdo_sqlsrv



 Description   

It's quite simple. Check out this method:

public function listFechas()
{
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery('
SELECT do.fecha
FROM ReplicacionBundle:DatoObjetivo do
GROUP BY do.fecha
ORDER BY do.fecha DESC
');
return $query->getResult();
}

Well, aparently this method is OK but when I call it from anywhere I get back a "500 Internal Server Error - PDOException", so I decided to check the generated SQL using the PHP function echo() and this is the output:

SELECT [0_.fecha AS fecha0 FROM [datobjbar] [0_ GROUP BY [0_.fecha ORDER BY [0_.fecha DESC

There is a missing "]" at the end of any of the generated "[0_", the correct expression would be "[0_]". Look at it carefully.

Can anyone can tell me how can I fix this??



 Comments   
Comment by Benjamin Eberlei [ 18/Jul/12 ]

Can you post the mapping/php files of DatoObjectivo?

Comment by Osain J. Fdez. Rguez. [ 18/Jul/12 ]

Here it is, if you need anything else just let me know. Thanks a lot.

<?php

/**

  • Objectives power lost data.
    *
  • @author Osain
    */

namespace Despacho\ReplicacionBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Despacho\ReplicacionBundle\Entity\Objetivo;

/**

  • @ORM\Table(name="datobjbar")
  • @ORM\Entity(repositoryClass="Despacho\ReplicacionBundle\Entity\DatoObjetivoRepository")
    */
    class DatoObjetivo {

/**

  • @ORM\Id
  • @ORM\ManyToOne(targetEntity="Objetivo", inversedBy="datosobjetivo", cascade= {"remove"}

    )

  • @ORM\JoinColumn(name="idbarra", referencedColumnName="idbarra")
    */
    private $objetivo;

/**

  • @ORM\Id
  • @ORM\Column(type="datetime")
  • @Assert\NotBlank()
    */
    private $fecha;

/**

  • @ORM\Column(type="decimal")
    */
    private $entrega;

/**

  • @ORM\Column(type="decimal")
    */
    private $recibe;

/**

  • Set fecha
    *
  • @param datetime $fecha
    */
    public function setFecha($fecha) { $this->fecha = $fecha; }

/**

  • Get fecha
    *
  • @return datetime
    */
    public function getFecha() { return $this->fecha; }

/**

  • Set entrega
    *
  • @param decimal $entrega
    */
    public function setEntrega($entrega) { $this->entrega = $entrega; }

/**

  • Get entrega
    *
  • @return decimal
    */
    public function getEntrega() { return $this->entrega; }

/**

  • Set recibe
    *
  • @param decimal $recibe
    */
    public function setRecibe($recibe) { $this->recibe = $recibe; }

/**

  • Get recibe
    *
  • @return decimal
    */
    public function getRecibe() { return $this->recibe; }

/**

  • Set objetivo
    *
  • @param Despacho\ReplicacionBundle\Entity\Objetivo $objetivo
    */
    public function setObjetivo(Objetivo $objetivo) { $this->objetivo = $objetivo; }

/**

  • Get objetivo
    *
  • @return Despacho\ReplicacionBundle\Entity\Objetivo
    */
    public function getObjetivo() { return $this->objetivo; }

    }

Comment by Osain J. Fdez. Rguez. [ 20/Jul/12 ]

Ok, for future references here is the problemn solved. It results the class Doctrine\ORM\Query\SqlWalker has a special method to generate a unique, short SQL table alias. Original declaration as follows:

/**

  • Generates a unique, short SQL table alias.
    *
  • @param string $tableName Table name
  • @param string $dqlAlias The DQL alias.
  • @return string Generated table alias.
    */
    public function getSQLTableAlias($tableName, $dqlAlias = '')
    {
    $tableName .= ($dqlAlias) ? '@[' . $dqlAlias . ']' : '';

if ( ! isset($this->_tableAliasMap[$tableName]))

{ $this->_tableAliasMap[$tableName] = strtolower(substr($tableName, 0, 1)) . $this->_tableAliasCounter++ . '_'; }

return $this->_tableAliasMap[$tableName];
}

The problem is that this method doesn't consider the fact that tables in MS SQL platform queries starts with '[' and ends with ']' so I made some modifications and all went perfectly OK. Check this out:

public function getSQLTableAlias($tableName, $dqlAlias = '')
{
$tableName .= ($dqlAlias) ? '@[' . $dqlAlias . ']' : '';

if ( ! isset($this->_tableAliasMap[$tableName]))

{ if($this->_platform->getName() == 'mssql') $this->_tableAliasMap[$tableName] = '[' . strtolower(substr($dqlAlias, 0, 1)) . $this->_tableAliasCounter++ . ']'; else $this->_tableAliasMap[$tableName] = strtolower(substr($tableName, 0, 1)) . $this->_tableAliasCounter++ . '_'; }

return $this->_tableAliasMap[$tableName];
}





[DDC-1926] Foreign keys in composite primary keys Created: 14/Jul/12  Updated: 14/Jul/12  Resolved: 14/Jul/12

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

Type: New Feature Priority: Major
Reporter: Maxime Corbeau Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None


 Description   

As currently state on the limitations and known issues page, Doctrine 2 offers support for "composite primary keys that does not currently include foreign keys as primary key columns".

I am currently running 2.3.0-DEV, and can confirm there is a problem: Doctrine simply does not generate entities for tables which primary key is composed of foreign keys, as I explained it on StackOverflow. The given workaround of using a surrogate key instead and adding a unique constraint on foreign keys (as a single constraint) does solve the issue.

However, having primary keys composed of foreign keys is a basic database design which in my case is used in a lot of database schemas, and having to change those schemas to fit Doctrine requires extra work and makes your schemas Doctrine-oriented, whereas IMO they should remain neutral as it facilitates collaboration with non-Doctrine specialized developers and interoperability with other systems. Hence this feature request to have Doctrine support composite primary keys including foreign keys.



 Comments   
Comment by Benjamin Eberlei [ 14/Jul/12 ]

You are using the 2.0.x docs. This is possible since 2.1 with

/**
 * @Id
 * @ManyToOne(targetEntity="Related")
 */
Comment by Maxime Corbeau [ 14/Jul/12 ]

Maybe I'm being thick (which is always a possibility), but the entity which corresponds to the table with the primary key composed of foreign keys doesn't even get generated when I run "orm:convert-mapping" and "orm:generate-entities" (unlike entities for the other tables), therefore I'm wondering: where am I supposed to insert the snippet you provided?





[DDC-1907] RemoveMethod generation doesn't exist Created: 04/Jul/12  Updated: 04/Jul/12  Resolved: 04/Jul/12

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Tools
Affects Version/s: 2.2.2
Fix Version/s: 2.2.3

Type: Bug Priority: Major
Reporter: Xorrox Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: None
Environment:

Symfony2



 Description   

Symfony2 test existence of AddMethod and RemoveMethod and tools doesn't generate RemoveMethod on Many Relation

CF : symfony2/dev-master Symfony/Component/Form/Util/PropertyPath.php Line 535



 Comments   
Comment by Benjamin Eberlei [ 04/Jul/12 ]

Fixed





[DDC-1875] "Call to a member function toArray() on a non-object" in PersistentCollection::takeSnapshot() during LEFT JOIN Created: 15/Jun/12  Updated: 22/Jun/14  Resolved: 06/Oct/12

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

Type: Bug Priority: Major
Reporter: Jelmer Schreuder Assignee: Benjamin Eberlei
Resolution: Cannot Reproduce Votes: 0
Labels: None
Environment:

Windows + latest XAMPP



 Description   

I am getting the fatal error "Call to a member function toArray() on a non-object" which is triggered in Doctrine/ORM/PersistentCollection.php on line 239 by $this->snapshot = $this->coll->toArray();

SELECT i, c FROM Page i
LEFT JOIN i.children c
WHERE i.parent_id IS NULL
	AND i.site = ?1
ORDER BY i.id ASC

The association is self-referential on the column parent_id. Removing "LEFT" from the query makes is run successfully (but ofc not in the way I need it). Making it only select 'i' instead of 'i, c' also solves it. But I don't think it's wrong in it's current form is it?

The Entity (slightly truncated to remove personal/local info) is at http://scrp.at/bvl



 Comments   
Comment by Benjamin Eberlei [ 05/Jul/12 ]

can you paste the full stack trace when the error occurs? Xdebug shows this.

Comment by Benjamin Eberlei [ 06/Oct/12 ]

No feedback given and cannot reproduce.

Comment by Oleg Kolomiets [ 21/Jun/14 ]

( ! ) Fatal error: Call to a member function toArray() on a non-object in /var/www/html/mktl/vendor/doctrine/orm/lib/Doctrine/ORM/PersistentCollection.php on line 245
Call Stack

  1. Time Memory Function Location
    1 0.0001 233752
    Unknown macro: {main}

    ( ) ../index.php:0
    2 0.0003 234472 require_once( '/var/www/html/mktl/public/app.php' ) ../index.php:17
    3 0.0573 3065184 Zend\Mvc\Application->run( ) ../app.php:33
    4 0.0590 3100288 Zend\EventManager\EventManager->trigger( ) ../Application.php:309
    5 0.0590 3100336 Zend\EventManager\EventManager->triggerListeners( ) ../EventManager.php:207
    6 0.0594 3108144 call_user_func:

    Unknown macro: {/var/www/html/mktl/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php}

    ( ) ../EventManager.php:468
    7 0.0594 3108712 Zend\Mvc\DispatchListener->onDispatch( ) ../EventManager.php:468
    8 0.0600 3169304 Zend\Mvc\Controller\AbstractController->dispatch( ) ../DispatchListener.php:114
    9 0.0600 3169784 Zend\EventManager\EventManager->trigger( ) ../AbstractController.php:117
    10 0.0600 3169832 Zend\EventManager\EventManager->triggerListeners( ) ../EventManager.php:207
    11 0.0604 3185720 call_user_func:

    Unknown macro: {/var/www/html/mktl/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php}

    ( ) ../EventManager.php:468
    12 0.0604 3186312 Admin\AController->onDispatch( ) ../EventManager.php:468
    13 0.0746 4270960 Zend\Mvc\Controller\AbstractActionController->onDispatch( ) ../AController.php:159
    14 0.0747 4271224 Admin\Controller\BrandsController->editAction( ) ../AbstractActionController.php:83
    15 0.0751 4313696 Products\Repositories\BrandRepository->find( ) ../BrandsController.php:70
    16 0.0761 4451448 Doctrine\ORM\AbstractQuery->getResult( ) ../BrandRepository.php:60
    17 0.0761 4451808 Doctrine\ORM\AbstractQuery->execute( ) ../AbstractQuery.php:542
    18 0.0768 4473080 Doctrine\ORM\Internal\Hydration\AbstractHydrator->hydrateAll( ) ../AbstractQuery.php:751
    19 0.0769 4477328 Doctrine\ORM\Internal\Hydration\ObjectHydrator->hydrateAllData( ) ../AbstractHydrator.php:111
    20 0.0781 4673184 Doctrine\ORM\PersistentCollection->takeSnapshot( ) ../ObjectHydrator.php:155

Comment by Marco Pivetta [ 22/Jun/14 ]

Are the mappings passing validation?





[DDC-1821] Doctrine tool generates classes who's meta data cannot be read by annotation driver Created: 15/May/12  Updated: 04/Jul/12  Resolved: 04/Jul/12

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers, ORM
Affects Version/s: 2.2.1
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Jonathan Robinson Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None
Environment:

Debian, Php 5.3



 Description   

I have xml files defining entities. These get turned into classes via doctrine tool.

The doctrine tool generates metadata with "Doctrine\ORM\Mapping" proceeding the metaname.

for example:

use Doctrine\ORM\Mapping as ORM;

/**

  • Person
    *
  • @ORM\Table(name="person")
  • @ORM\Entity
    */

This breaks the annotation reader.

If I manually change the class to look like:

/**

  • Person
    *
  • @Table(name="person")
  • @Entity
    */

Everything works happily.



 Comments   
Comment by Marco Pivetta [ 08/Jun/12 ]

Not a bug. It is suggested to use the AnnotationReader instead of the SimpleAnnotationReader.

Comment by Benjamin Eberlei [ 04/Jul/12 ]

You have to set $generator->setAnnotationPrefix("");





[DDC-1794] DriverChain unable to load mixed Drivers at given sort of load. Created: 22/Apr/12  Updated: 05/Jul/12  Resolved: 05/Jul/12

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers
Affects Version/s: 2.2.2
Fix Version/s: None

Type: Bug Priority: Major
Reporter: feathers and down Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None
Environment:

openSUSE 12.1, Apache 2.2.21


Attachments: Zip Archive doctrine_full.zip    

 Description   

From doctrine mailing list http://groups.google.com/group/doctrine-user/browse_thread/thread/86b9a732f3cc1626

I'm trying to load different mappings methods using DriverChain. My example code is from bug tracker tutorial. I have 3 classes under 'entities' folder: Bug, Product, User that have Annotations and Yaml mapping files, then I've added two more entities under 'entities_1' folder: BugStatus and Client with Annotations and Xml mapping files. 'status' field from Bug table point to BugStatus id, same thing to 'client' field from Client that point to Product. I know is a bad design, is only for test. So you can see, there is a dependency from first three files to last two classes.

My tests are only using console with: php doctrine orm:info

1) I can load last two files using Annotations and Xml, so they work as stand alone.

Annotations-Xml, Xml-Annotations
2) At run time, first I load three files from 'entities' using Annotations, then load two files from 'entities_1' using Xml and both work. (info appear [OK] in all 5 classes).
3) At run time, first I load two files from 'entities_1' using Xml, then load three files from 'entities' using Annotations and both work too.

Annotations-Yaml, Yaml-Annotations
4) At run time, first I load two files from 'entities_1' using Annotation driver, then load three files from 'entities' using Yaml driver and both work.
5) At run time, first I load three files from 'entities' using Yaml driver, then load two files from 'entities_1' using Annotation driver and fail with this error:

----------
jago@jagobook:/media/Documentos/Programacion/localhost/doctrine_full/libraries/Doctrine/bin> php doctrine orm:info
Found 5 mapped entities:
[OK] Entities\Bug
[OK] Entities\Product
[OK] Entities\User
[FAIL] Entities_1\BugStatus
No mapping file found named 'Entities_1.BugStatus.dcm.yml' for class 'Entities_1\BugStatus'.

[FAIL] Entities_1\Client
No mapping file found named 'Entities_1.Client.dcm.yml' for class 'Entities_1\Client'.

jago@jagobook:/media/Documentos/Programacion/localhost/doctrine_full/libraries/Doctrine/bin>
-----------

Seem that search metadata from Yaml configuration, when they are added to DriverChain using Annotation driver:

-----------
//YAML
require_once '../../../entities/Bug.php';
require_once '../../../entities/Product.php';
require_once '../../../entities/User.php';
$path = '/media/Documentos/Programacion/localhost/doctrine_full/entities/mapping';
$yaml = new \Doctrine\ORM\Mapping\Driver\YamlDriver( array( $path ) );
$dc->addDriver( $yaml, "Entities" );

//Annotations
$path = '/media/Documentos/Programacion/localhost/doctrine_full/entities_1';
$an2 = $config->newDefaultAnnotationDriver( $path );
$dc->addDriver( $an2, "Entities_1" );

$config->setMetadataDriverImpl( $dc );
--------------

Or I miss something?

Thanks in advance.

Some screenshots, see in transparent console code from NetBeans
------------
annotations then xml
http://i.imgur.com/BfIKC.png

xml then annotations
http://i.imgur.com/hqsJ0.png

--------------

annotations then yaml
http://i.imgur.com/Linrs.png

yaml then annotations (error)
http://i.imgur.com/gctpI.png



 Comments   
Comment by Benjamin Eberlei [ 05/Jul/12 ]

this obviouisly doesnt work, as Entities match Entities_1 already. You have to sort them in reverse order to make it working.





[DDC-1790] Allow ORDER BY and LIMIT for UPDATE queries Created: 19/Apr/12  Updated: 19/Apr/12  Resolved: 19/Apr/12

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: DQL
Affects Version/s: 2.1.4
Fix Version/s: None

Type: New Feature Priority: Major
Reporter: Tim Hemming Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None
Environment:

Symfony2 project using MySQL persistence layer.



 Description   

I'm trying to update n-number of rows from a table (ordered by created timestamp) but the update query (built in either DQL or using the query builder) does not support ORDER BY or LIMIT on UPDATE statements.

Is it possible to allow these two clauses in UPDATE statements?

Example DQL is:
UPDATE ICFeederBundle:QueuedLead l SET l.lockId=:lockId WHERE l.lockId IS NULL ORDER BY l.created ASC LIMIT 10



 Comments   
Comment by Benjamin Eberlei [ 19/Apr/12 ]

This is mysql specific functionality and therefore cannot be supported in DQL.





[DDC-1731] Unable to Simply Get Foreign Identifier in SELECT Created: 28/Mar/12  Updated: 01/Apr/12  Resolved: 01/Apr/12

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: DQL
Affects Version/s: 2.1.5
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Kevin Herrera Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None


 Description   

This DQL

SELECT r.type FROM record r

Will trigger this error:

[Semantical Error] line 0, col 9 near 'type': Error: Invalid PathExpression. Must be a StateFieldPathExpression. #0

When this DQL won't:

SELECT f.id FROM record r JOIN r.type f

This is computationally expensive when working with hundreds of thousands of records.



 Comments   
Comment by Benjamin Eberlei [ 01/Apr/12 ]

SELECT IDENTITY(r.type) AS id FROM Record r





[DDC-1688] Entity Manager not using cache when using find() function Created: 06/Mar/12  Updated: 06/Mar/12  Resolved: 06/Mar/12

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

Type: Bug Priority: Major
Reporter: Florin Patan Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None
Environment:

Ubuntu 11.10, standard composer install of symfony2.1 and doctrine 2.2.1



 Description   

Hello,

It seem that when I'm doing something like: $g = $this->getDoctrine()>getManager('default')>find('AcmeDemoBundle:User', 5); the query is executed every time even if the cache is set to use APC for both the query and the results.

Doing a query via QueryBuilder and setting the cache explicitly will take advantage of the caching mechanism but I believe this shouldn't be the default way of working for caching.

I mean that if I configure the cache to be used, one would expect it to work.



 Comments   
Comment by Benjamin Eberlei [ 06/Mar/12 ]

Caching only works for DQL as of now.

There are tickets that cover the other stuff, which is a feature request.





[DDC-1712] proxy calss constructor do not call it's parent constructor Created: 16/Mar/12  Updated: 16/Mar/12  Resolved: 16/Mar/12

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.2-BETA2
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Marc Drolet Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None


 Description   

I've create a OneToMany relation in my entity and into the entity constructor I define my relation property to be an ArrayCollection.
When I load an existing entity that have no entries from it's relation, I'm waiting to receive an empty ArrayCollection but I got null into the proxy entity object cause my parentEntity __consctruct is never called from the proxyEntity __construct class.

ORM/Proxy/ProxyFactory.php line 356. <-- this is where the proxy class __construct method is generated.

I'm following the Best Practice manuel

http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/best-practices.html
25.8. Initialize collections in the constructor



 Comments   
Comment by Benjamin Eberlei [ 16/Mar/12 ]

Proxies are only created for classes coming from persistence. Classes reconstructed from persistence don't call the constructor but only __wakeup and then populate all the collections from persistence.





[DDC-1710] Undefined index Created: 16/Mar/12  Updated: 16/Mar/12  Resolved: 16/Mar/12

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

Type: Bug Priority: Major
Reporter: marksman Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None
Environment:

ubuntu server, symfony2



 Description   

TwitterTweets entity: http://pastecode.com/u6

TwitterUsers entity: http://pastecode.com/u7

So, when i select a TwitterTweets record with findBy method...
$this->getDoctrine()>getRepository('TwitterTweets')>findOneBy(array( 'tweetId' => $data->tweet_id ))

i get this error:

[{"message":"Notice: Undefined index: id in \/var\/mobminds\/vendor\/doctrine\/lib\/Doctrine\/ORM\/UnitOfWork.php line 2018","class":"ErrorException" ...






[DDC-1665] Reading different part of aggregates always give the first part Created: 22/Feb/12  Updated: 05/Mar/12  Resolved: 03/Mar/12

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

Type: Bug Priority: Major
Reporter: Francesco Montefoschi Assignee: Benjamin Eberlei
Resolution: Can't Fix Votes: 0
Labels: None


 Description   

Let's suppose to have a one-to-many relation like User -> Address.

If I do a query like:
SELECT User, Address FROM ..
WHERE User.id = 1 AND Address.id = 111

I get the User object with the collection Addresses composed by only one element - AddressId=111

Now I do another query:
SELECT User, Address FROM ..
WHERE User.id = 1 AND Address.id = 222

but this time I do not get the User with Addresses collection composed by only element wih AddressId=222. I get the previous object like the query were not executed at all.

Now, I understand that the User is already known by Doctrine and Doctrine cannot handle two instances of the same table row. But this is confusing in development: a developer would expect an object with what you queried (Address with id=222).

Right now I do em->detach(User) between the two query so I force Doctrine to really execute the second query and give me what I want. It's enough since I do not need to update User nor Address when I load a partial aggregate, but I'm not sure if this is a good practice.



 Comments   
Comment by Francesco Montefoschi [ 22/Feb/12 ]

I forgotten to specify that I am not loading just one Address because I like to it, but because my collection can be very very large (1000-2000 Addresses) and I do not want to load all address to work only on two of them

Comment by Benjamin Eberlei [ 03/Mar/12 ]

This is a known problem and cannot be fixed, you have to work around it by hydrating the adress as a non-object, for example

SELECT User, Address.street, Address.city, ... FROM
Comment by Francesco Montefoschi [ 05/Mar/12 ]

Yes, it can be work arounded by hydrating as array for example, but you cannot call model methods.

Anyone knows how Hibernate handle this?





[DDC-1647] DateTime field returns to string if used in association Created: 10/Feb/12  Updated: 20/Feb/12  Resolved: 20/Feb/12

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers, ORM
Affects Version/s: 2.1.4
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Alexey Shockov Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None
Environment:

PHP 5.3.9, MySQL 5.5, Debian 6.



 Description   

I have two objects with one-to-many accociation, based on date ("date" type column in all two objects):

@ORM\JoinColumn(name="date", referencedColumnName="date"),

When I establish accociation, I get strange behaviour — without association date was DateTime, after — string.



 Comments   
Comment by Benjamin Eberlei [ 10/Feb/12 ]

Since DateTime cannot be part of a PK it cannot be part of a join column. how does the full mapping look like?

Comment by Vyacheslav Salakhutdinov [ 13/Feb/12 ]
Blank.php
/**
 * @ORM\Entity
 */
class Blank
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     *
     * @var int
     */
    private $id;

    /**
     * @ORM\Column(type="date")
     *
     * @var \DateTime
     */
    private $date;
}
Sale.php
/**
 * @ORM\Entity
 */
class Sale
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     *
     * @var int
     */
    private $id;

    /**
     * @ORM\Column(type="date")
     *
     * @var \DateTime
     */
    private $date;

    /**
     * @ORM\ManyToOne(targetEntity="Blank", fetch="EAGER")
     * @ORM\JoinColumn(name="date", referencedColumnName="date")
     */
    private $blank;
}

$blank loading properly, but field "date" doesn't mapping to \DateTime

// without annotation on $blank
var_dump($sale->getDate()); // output "object(DateTime)#266..."
// with annotation on $blank
var_dump($sale->getDate()); // output "string(10) "2012-02-13""
Comment by Benjamin Eberlei [ 20/Feb/12 ]

This kind of association is not supported, you can only map towards the Primary key of another entity. "DateTime" type cannot be part of the primary key, you have to map it as string to get it working. Sorry, these are two restrictions that greatly simplify and speed up the internals of Doctrine and that we have to keep.





[DDC-1649] Triple split mapping issue with Doctrine2 Created: 13/Feb/12  Updated: 20/Feb/12  Resolved: 20/Feb/12

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.1, 2.1.1, 2.1.2, 2.1.3, 2.1.4, 2.1.5, 2.1.6, 2.2-BETA1, 2.2-BETA2, 2.2.0-RC1, 2.2
Fix Version/s: None

Type: Bug Priority: Major
Reporter: David Ichilov Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None
Environment:

OS independent. Pure Doctrine issue


Attachments: Text File tracesAndEntities.txt    

 Description   

For starters you can see discussion [here].

The issue arise then I have 3 (and I guess more) tables sharing their PK (split tables), for example.:

Table Auth which holds user_id PK.
Table OurUsers for which Auth.user_id is shared PK.
Table EmailVerification for which OurUsers.user_id is shared PK.
I also have NotOurUsers - hence the split.

Attached is Entity definitions.

with version 2.1 and 2.2 I'm able to add new records (insert) to EmailVerification but not to update them (stack trace #1 attached, for 2.2). And it failed mapping validation. It passes validation with 2.2.
with version 2.1 I was able to use EntityManager::find('EmailVerification', $objectOfOurUsers) calling the same with 2.2 produces error (stack trace #2 attached), with 2.2. I can only call EntityManager::find('EmailVerification', $objectOfOurUsers->getUser()->getID())



 Comments   
Comment by Benjamin Eberlei [ 20/Feb/12 ]

This issue is that you cannot map emailverification assoc to OurUsers which also an assoc mapping. This is not supported. I will add the SchemaValidator to hint for this issue.

Comment by David Ichilov [ 20/Feb/12 ]

Can it be supported in the future versions? Maybe adding it to feature request (if there is a list like that) will help?

PS
AFAIK Hibernate do support that kind of assoc.

Comment by Benjamin Eberlei [ 20/Feb/12 ]

Enhanced SchemaValidator.

A feature being in Hibernate is not a reason for us to have it too, you have to adjust for the different languages and such. Support for this is going to make the core much more complex, and definately slower. We have to weigh the pros and cons, and the complexity isn't worth it from my POV.





[DDC-1646] JoinColumn not working for associations throught another associations Created: 10/Feb/12  Updated: 03/Mar/12  Resolved: 03/Mar/12

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers, ORM
Affects Version/s: 2.1.4
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Alexey Shockov Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None
Environment:

PHP 5.3.9, MySQL 5.5, Debian 6.



 Description   

I have two objects: Sale and Blank. This two object doesn't associated directly, but association may be established using promoter_id and date database columns. But, when I wrote above code in Sale class:

@ORM\ManyToMany(targetEntity="Blank")
@ORM\JoinTable(
    name="blank",
    joinColumns={
        @ORM\JoinColumn(name="promoter_id", referencedColumnName="promoter_id"),
        @ORM\JoinColumn(name="date", referencedColumnName="date")
    },
    inverseJoinColumns={
        @ORM\JoinColumn(name="promoter_id", referencedColumnName="promoter_id"),
        @ORM\JoinColumn(name="date", referencedColumnName="date")
    }
)

I got error: "The column promoter_id must be mapped to a field in class Sale since it is referenced by a join column of another class".



 Comments   
Comment by Benjamin Eberlei [ 03/Mar/12 ]

Doctrine only allows mapping foreign keys to primary keys of other classes.





[DDC-1627] Create a common interface for all the [Entity|Document]Manager's Created: 30/Jan/12  Updated: 30/Jan/12  Resolved: 30/Jan/12

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

Type: Improvement Priority: Major
Reporter: Jonathan Cardoso Machado Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None


 Description   

It would be wonderful if were created a common interface for the Managers of the projects Doctrine ORM, CouchDB ODM, and MongoDB ODM. This would facilitate, for example, the creation of classes of service that does not take into account only the Doctrine ORM as a persistence and can therefore be easily exchanged for the MongoDB ODM if necessary, for example:

Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
 
interface IService {
    public function __construct( PersistenceManager $pm ); 
}

interface PersistenceManager {

    public function find();
    public function persist();
    public function remove();
    public function flush();
    public function getRepository();

    //...
}

class EntityManager implements PersistenceManager {
}

class DocumentManager implements PersistenceManager {
}


 Comments   
Comment by Benjamin Eberlei [ 30/Jan/12 ]

This interface does alrady exist and is called ObjectManager. Its in Doctrine\Common\Persistence

Comment by Jonathan Cardoso Machado [ 30/Jan/12 ]

@Eberlei Thanks, I did not know about the existence of these interfaces.





[DDC-1565] ClassMetadataInfo must implements the Doctrine\Common\Persistence\Mapping\ClassMetadata interface Created: 25/Dec/11  Updated: 29/Dec/11  Resolved: 29/Dec/11

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers, ORM
Affects Version/s: Git Master
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Kévin Dunglas Assignee: Benjamin Eberlei
Resolution: Can't Fix Votes: 0
Labels: None
Environment:

Doctrine Extensions



 Description   

The doctrine:generate:entities command from Symfony 2 fails when using Doctrine Extensions (i.e. Timestampable) with this error :

[ErrorException]
Catchable Fatal Error: Argument 2 passed to Gedmo\Mapping\MappedEventSubscriber::loadMetadataForObjectClass() must implement interface Doctrine\Common\Persistence\Mapping\ClassMetadata, instance of Doctrine\ORM\Mapping\ClassMetadataInfo given, called in /Users/dunglas/Documents/workspace/DoctrineExtensions/lib/Gedmo/Timestampable/TimestampableListener.php on line 44 and defined in /Users/dunglas/Documents/workspace/DoctrineExtensions/lib/Gedmo/Mapping/MappedEventSubscriber.php line 171

The error should also occurs without using Symfony because it's related to Doctrine and Doctrine Extensions.

In Doctrine MongoDB ODM this is ClassMetadataInfo that implements the Doctrine\Common\Persistence\Mapping\ClassMetadata and the problem does not occurs.

To do this the getIdentifierValues method of ClassMetadata must be moved to ClassMetadataInfo.



 Comments   
Comment by Benjamin Eberlei [ 28/Dec/11 ]

getIdentifierValues() uses reflection, and reflection code is exclusively in ClassMetadata.

The code here smells badly related to this distinction but i havent came up with a refactoring yet that solves this mess.

Comment by Benjamin Eberlei [ 29/Dec/11 ]

This is foremost a bug in Gedmos library, he hints for a ClassMetadata where none is expected.





[DDC-1531] Documentation references no-longer available constant Lexer::T_ABS Created: 13/Dec/11  Updated: 14/Dec/11  Resolved: 14/Dec/11

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Documentation
Affects Version/s: Git Master
Fix Version/s: 2.2

Type: Documentation Priority: Major
Reporter: Erik Bernhardson Assignee: Guilherme Blanco
Resolution: Fixed Votes: 0
Labels: None


 Description   

Line 645 of https://github.com/doctrine/orm-documentation/blob/master/en/reference/dql-doctrine-query-language.rst

Best i can tell this has been re-named to Lexar::T_IDENTIFIER by looking at other functions in the distribution



 Comments   
Comment by Guilherme Blanco [ 14/Dec/11 ]

Fixed in https://github.com/doctrine/orm-documentation/commit/373090f2232a59b7c4cb35212a1c1d5843bc8be7





[DDC-1460] Default nullable behavior when not explicitly defining joinColumns Created: 29/Oct/11  Updated: 16/Jan/12  Resolved: 16/Jan/12

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers, ORM
Affects Version/s: None
Fix Version/s: None

Type: Task Priority: Major
Reporter: Alexander Assignee: Guilherme Blanco
Resolution: Invalid Votes: 0
Labels: None


 Description   

Currently there is are no defaults set for 'nullable' on OneToOne and ManyToMany associations where joinColumns are not explicitly defined. I believe it should be nullable=true as a default in both cases.

I already added the OneToOne case in this commit (not merged yet, I had to check first):
https://github.com/asm89/doctrine2/commit/a175f39b3592af434b578853e916953bebeec910

Should I also add the 'nullable' => true as default if there are no join columns specified on a ManyToMany association?



 Comments   
Comment by Guilherme Blanco [ 16/Jan/12 ]

We already spoke about this and agreed this change is not good





[DDC-1388] ORMPurger truncate fails for referenced tables in MySQL Created: 22/Sep/11  Updated: 10/Oct/11  Resolved: 10/Oct/11

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

Type: Bug Priority: Major
Reporter: hans Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: None
Environment:

symfony2, mysql 5.5.8, windows7


Attachments: Text File fix_DDC-1388.patch    

 Description   

Running the doctrine:fixtures:load command in symfony2 invokes the doctrine ORMPurger, in my case for the MySQL platform, and throws following PDO Exception:

SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constraint (`sf2blog`.`comment`, CONSTRAINT `FK_9474526CDAE07E97` FOREIGN KEY (`blog_id`) REFERENCES `sf2blog`.`blog` (`id`))

That is because my comment table references the id column of the blog table and doctrine tries to truncate the blog table. To solve that you should run
SET foreign_key_checks=0;
prior to
TRUNCATE TABLE `blog`
and reactivate foreign key checks again
SET foreign_key_checks=0;

One way to achieve that would be to implement the getTruncateTableSQL method in the Doctrine\DBAL\Platforms\MySqlPlatform class.



 Comments   
Comment by hans [ 22/Sep/11 ]

Added a patch with the changes suggested in the description.

Comment by Benjamin Eberlei [ 10/Oct/11 ]

This was fixed by going back to delete by using a commandline switch. I need to check for a better fix.





[DDC-1361] DQL Hydrate issues with PK composed with composite FK seemingly making collections loaded twice Created: 04/Sep/11  Updated: 25/Sep/11  Resolved: 05/Sep/11

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: DQL, ORM
Affects Version/s: 2.1.1
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Cam Manderson Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: None


 Description   

Environment/Scenario:
==================

ENTITIES:
--------------
Page Entity (page)

  • page.id as PK
  • page.elements One to Many to entity elements (w/ ArrayCollection)

Elements Entity (element)

  • element.id AS PK
  • page (Many to One)
  • elementVersions One to Many to elementVersions entity (w/ ArrayCollection)

ElementVersion Entity (elementVersion)

  • element AND elementVersion.versionId as PK (note this is a PK composed of FK)
  • element Many to One to element entity

Repository
---------------
When using my Node Repository I do a DQL with all the joins, e.g.
DQL: SELECT page, element, elementVersions FROM page JOIN page.elements AS element JOIN page.elementVersion AS elementVersion WHERE page.id = :pageId.

By doing this all the data is loaded correctly. This is shown by doing a var_dump on a HYDRATE_ARRAY. The structure is correct. There is one thing that appears missing elementVersion.element, therefore not having a complete PK present (TBD). I would think that there should be a reference back to the parent (element).

I then switched back to hydrating my entity objects as normal. I should have loaded all the data into the collections therefore stopping any need to do subsequent DB calls.

Problem/Bug
==========
When I access the collection for the versions (e.g. page.elements.elementVersions) the elementVersions are reloaded again from the database. (e.g. A new SQL call is made to the server), even though my first join had loaded the data.

I believe that when it is using a FK in the PK composition it is not correctly seeing it has loaded the data already.

Weird Behaviour
=============
If I do a DQL that joins the relationship back, I can avoid the database reloading the collection again:

SELECT page, element, elementVersion, elementVersionElement FROM page JOIN page.elements AS element JOIN page.elementVersions AS elementVersion JOIN elementVersion.element AS elementVersionElement WHERE page.id = :pageId.

By joining the table that is used for the FK/PK scenario back onto itself it prevents another SQL call being made when I attempt to access page.elements.elementVersions.

If I switch back to HYDRATE_ARRAY, I can see that now the elementVersions have the element variable, and it appears that this allows it to identify that it has it in the collection and no-longer needs to re-run SQL to locate the object again.

This results in unavoidable additional SQL calls for each element that exists on the page (scales proportionate to number of elements).

My Thoughts
==========
I am thinking that in the hydrate process it is not setting the FK relationship of elementVersion.element, causing Doctrine to attempt to re-run SQL to obtain the collection again (maybe because it thinks that the objects do not have valid/complete PK). I think somewhere the mapping when it creates the objects is just missing the bit where the proxy gains a value for this property back to the parent.



 Comments   
Comment by Cam Manderson [ 04/Sep/11 ]

I missed some backwards links between the element and the page.

Comment by Cam Manderson [ 04/Sep/11 ]

I am developing a test case for this issue. Will share github link. thanks

Comment by Cam Manderson [ 05/Sep/11 ]

Realised when I was doing PHP Unit Testing that I was getting some index undefined issues. It was around the generation of Hash values in the ObjectHydrator:217.

It was attempting to look at the $data for the FK element. In my example: undefined index element. By making it look up the associationMappings for the field name element it would be referencing the correct field value.

Updated around lines 217 as follows:

foreach ($class->identifier as $fieldName) {
// Add in if the class identifier has data from an associative mapping
if (isset($class->associationMappings[$fieldName]))

{ $idHash .= $data[$class->associationMappings[$fieldName]['joinColumns'][0]['name']]; }

else

{ $idHash .= $data[$fieldName]; }

}

Not sure of the practice to submit a pull request. I am assuming I need corresponding test cases?

Comment by Cam Manderson [ 05/Sep/11 ]

Found this was a duplicate issue of DDC-1300.





[DDC-1369] "throw" keyword missing in _getCollectionOrderBySQL Created: 09/Sep/11  Updated: 25/Sep/11  Resolved: 25/Sep/11

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

Type: Bug Priority: Major
Reporter: Kees Schepers Assignee: Benjamin Eberlei
Resolution: Won't Fix Votes: 0
Labels: None
Environment:

Ubuntu desktop, PHP 5.3.3, MySQL 5.1.49



 Description   

In the BasicEntityPersister.php around line 901 there proberly is a keyword "throw" missing in the function _getCollectionOrderBySQL.

The following code:
if ( ! isset($this->_class->fieldMappings[$fieldName]))

{ ORMException::unrecognizedField($fieldName); }

Should be:
if ( ! isset($this->_class->fieldMappings[$fieldName]))

{ throw ORMException::unrecognizedField($fieldName); }

In my case because of this keyword missing Doctrine tried to execute a query like:

SELECT t0.id AS id1, t0.stockprice AS stockprice2, t0.productoptionvalueid AS productoptionvalueid3, t0.productid AS productid4 FROM productoptionvalue_to_product t0 WHERE t0.productid = '1852' ORDER BY t0. ASC



 Comments   
Comment by Benjamin Eberlei [ 25/Sep/11 ]

This bug is fixed in 2.1 and its priority is trivial, i won't fix it in 2.0 anymore, please upgrade to 2.1





[DDC-1319] AnnotationDriver is not able to find the FETCH_EXTRA_LAZY constant in ClassMetadata (and it is in superior ClassMetadataInfo) Created: 05/Aug/11  Updated: 13/Sep/11  Resolved: 13/Sep/11

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

Type: Bug Priority: Major
Reporter: Jiri Helmich Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None
Environment:

FreeBSD 8.2-PRERELEASE
Apache/2.2.17 (FreeBSD) mod_ssl/2.2.17 OpenSSL/0.9.8q PHP/5.3.5 with Suhosin-Patch



 Description   

PHP Warning: constant(): Couldn't find constant Doctrine\ORM\Mapping\ClassMetadata::FETCH_EXTRA_LAZY in

{...}

/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php on line 304

  • @OneToMany(targetEntity="Photos", mappedBy="owner", fetch="EXTRA_LAZY")


 Comments   
Comment by Benjamin Eberlei [ 06/Aug/11 ]

i don't know how this could happen. This works for me without notice.

Comment by Jiri Helmich [ 09/Aug/11 ]

Still experiencing this :/. I'll try to fetch a more detailed stack trace and provide more information.

Comment by Jiri Helmich [ 13/Sep/11 ]

It seems that I'm no longer able to reproduce that
Sorry for bothering you





[DDC-1289] orm:generate-entities create incorrect setters for ManyToOne and OneToOne Created: 23/Jul/11  Updated: 26/Jul/11  Resolved: 26/Jul/11

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers, ORM, Tools
Affects Version/s: 2.1
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Matthew Larson Assignee: Benjamin Eberlei
Resolution: Won't Fix Votes: 0
Labels: None


 Description   

When using the CLI tool to generate entities, ManyToOne setters are not being written correctly when the key-field is allowed to be null.

For example, on this annotation:

/** 
 *@OneToOne(targetEntity="AdminRole")
 */
protected $adminRole;

the following method is created:

public function setAdminRole(\path\to\namespace\AdminRole $adminRole)
{...}

HOWEVER: the method declaration should be like this:

public function setAdminRole(\path\to\namespace\AdminRole $adminRole = null)
{...}

This allows for setting null values without throwing an error. As it is currently, this is only correct when the annotation includes @joinColumn(... nullable=false)



 Comments   
Comment by Benjamin Eberlei [ 26/Jul/11 ]

While this issue is valid i still won't fix it. The EntityGenerator is not meant to solve every use case but to give you a heads start if you are using XML and YAML as mapping. Doctrine 2 is not Doctrine 1 and clearly not Propel. Code-Generation is only a secondary if not tertiary requirement.





[DDC-3753] ManyToMany Relations from Value objects Created: 03/Jun/15  Updated: 03/Jun/15  Resolved: 03/Jun/15

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

Type: Bug Priority: Minor
Reporter: Maximilian Bosch Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: mapping, mysql, orm
Environment:

Ubuntu 14.04 (Virtualbox)/PHP 5.5.25/MySQL 5.5.43


Attachments: PNG File doctrine-user.PNG     PNG File doctrine-userdetails.PNG     PNG File doctrine-vm.PNG    

 Description   

I was trying to setup a many-to-many and a one-to-one relation from an embeddable object, but doctrine ignores these relation columns/tables (see screenshots).
As you can see, I've created a relation for followers called SEN_Following and SEN_UserToRole, but when reviewing the tables on the mysql, these tables are not shown.

When executing "php app/console doctrine:schema:update" I get the following message:
Nothing to update - your database is already in sync with the current entity metadata.



 Comments   
Comment by Maximilian Bosch [ 03/Jun/15 ]

in order to review the whole code, I've pushed to a remote feature branch on github: https://github.com/Ma27/SenNetwork/tree/SenNetwork-108

Comment by Marco Pivetta [ 03/Jun/15 ]

Value Objects should not reference entities in any case.

Comment by Maximilian Bosch [ 03/Jun/15 ]

ok thanks.

but just out of interest: why shouldn't they do??

Comment by Marco Pivetta [ 03/Jun/15 ]

Maximilian Bosch a value object can be compared with another value object by its value, whereas an entity is compared via identifier.

If you include an entity inside your VO you are comparing also the entity state (which is not comparable except for the identifier), and that breaks the entire idea of VO.

VOs should only reference other VOs and primitive types.

Comment by Maximilian Bosch [ 03/Jun/15 ]

Marco Pivetta thank you for your explanation.
but is there a way, how to persist collections inside a value objects??

serialization is IMHO a bad idea. For example I'd like to create a list which shows all users having a specific role, I had to load all users and the UserDetail object and check if they have the value object. With another table I could write a query for that.

Comment by Marco Pivetta [ 03/Jun/15 ]

but is there a way, how to persist collections inside a value objects??

currently not, and I'd still suggest serialization as a fallback (serialization is usually supported by VOs)

Comment by Maximilian Bosch [ 03/Jun/15 ]

Marco Pivetta ok thank you for your help.

I think the simplest solution is moving these relations into the entity and waiting for that feature.
The problem I'll ran into with serialization is that it's virtually impossible to query against a serialized string





[DDC-3418] Indexes not inherited from mapped superclass Created: 27/Nov/14  Updated: 27/Nov/14  Resolved: 27/Nov/14

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers
Affects Version/s: 2.4.6
Fix Version/s: 2.5

Type: Improvement Priority: Minor
Reporter: Dustin Thomson Assignee: Marco Pivetta
Resolution: Fixed Votes: 0
Labels: ddl, index, inheritance, mappedsuperclass, mapping

Issue Links:
Duplicate
duplicates DDC-3419 [GH-1196] Inherit indexes from mapped... Resolved
Reference
relates to OXM-2 Mapped-superclass, indexes not gathered Open
relates to DDC-3273 EntityGenerator writes @ORM\Table ann... Open

 Description   

Index definitions on mapped super classes are not inherited by their sub-classes.
I realize this makes the definition of the mapped super-class look a bit weird as it requires it to have a @Table element which isn't strictly valid since there is no corresponding table in the database.
However, it would be nice to set indices on the mapped superclass where the fields are actually defined as this increased comprehension and reduces maintenance.



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

Handled in DDC-3419





[DDC-3393] Cannot extend existing internal functions Created: 17/Nov/14  Updated: 17/Nov/14  Resolved: 17/Nov/14

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

Type: Bug Priority: Minor
Reporter: Rob Spick Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: None


 Description   

On the MySQL platform, i want to use DATE_SUB with more than just DAY and MONTH, so I write a function and give it the identifier of date_sub however this is not allowed?

Why are we not able to extend the functions, surely if we're writing the function we know the platform that we're extending it on and the other platform specific functions will fail at parsing due to an unsupported type.

I don't want to have to prefix my code with MY_DATE_SUB only for an additional type to be supported at a later date, that would just lead to inconsistencies in my code.



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

Overriding DQL functions may have terrible and unforeseen consequences when dealing with any codebase. If you have a specific use-case, use a specific DQL function, but do not try overriding an existing one that may be used in ways that you are not aware of.





[DDC-3330] Bad Pagination - rows with sorted collection Created: 29/Sep/14  Updated: 16/Jun/15  Resolved: 16/Jun/15

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: Git Master
Fix Version/s: 2.5.1

Type: Bug Priority: Minor
Reporter: Thomas Lallement Assignee: Bill Schaller
Resolution: Fixed Votes: 0
Labels: paginator, tests
Environment:

Ubuntu 12.04, PHP 5.5.3


Attachments: File DDC3330Test.php    

 Description   

I use the Doctrine Paginator to be able to have a correct pagination with collection.
I followed the documentation here:
http://doctrine-orm.readthedocs.org/en/latest/tutorials/pagination.html

It works well in most cases but there is a problem when ordering on a property of the entity + on an other property of the collection.

See the failing unit test I joined to this ticket.



 Comments   
Comment by Bill Schaller [ 16/Jun/15 ]

Closed PR via manual merge





[DDC-3270] abstract class database entity generation Created: 23/Aug/14  Updated: 19/Oct/14  Resolved: 19/Oct/14

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

Type: Bug Priority: Minor
Reporter: Yan Ni Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: mysql, orm
Environment:

WAMP symfony2



 Description   

I create an abstract class A using @ORM annotations, then create class B which is a subclass of class A. When I use these to update the mysql database, however, a table for class A was also generated, which shouldn't have happened(because class A is an abstract class).



 Comments   
Comment by Marco Pivetta [ 19/Oct/14 ]

abstract types in the ORM are called MappedSuperclass}}es. The fact that a class is {{abstract doesn't mean that it has no concrete table representing it.





[DDC-3261] Bad link in 34.3 Advanced Configuration - Connection Options Created: 20/Aug/14  Updated: 19/Oct/14  Resolved: 19/Oct/14

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Documentation
Affects Version/s: None
Fix Version/s: 2.5

Type: Documentation Priority: Minor
Reporter: Matthew Turland Assignee: Marco Pivetta
Resolution: Fixed Votes: 0
Labels: documentation, orm


 Description   

The link to the DBAL section from 34.3 Advanced Configuration - Connection Options results in a 404 HTTP response. This line appears to be responsible.

Link URL as it appears in the current documentation:
http://docs.doctrine-project.org/dbal/2.0/docs/reference/configuration/en






[DDC-3223] Failing test (get id return string type) Created: 22/Jul/14  Updated: 17/Jan/15  Resolved: 17/Jan/15

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: Git Master
Fix Version/s: 2.5

Type: Bug Priority: Minor
Reporter: Thomas Lallement Assignee: Marco Pivetta
Resolution: Fixed Votes: 0
Labels: identifier, lazy-loading, proxy, type
Environment:

Linux Ubuntu 13.10 / PHP 5.5.3 / Mysql 5.5.x


Issue Links:
Dependency
depends on DDC-3387 [GH-1182] #1086 identifier type in pr... Resolved

 Description   

I found an issue in a specific case, when you find a child entity (JOINED) which is linked to another child entity.

If I clone the linked child entity and call getId(), it gives the value as 'string' rather than 'integer'. If I set the property id as public, there is no problem.

If I call getId on the child entity rather than the clone, it gives 'integer' as expected. So it's weird...

See failing test here: https://github.com/doctrine/doctrine2/pull/1086



 Comments   
Comment by Doctrine Bot [ 11/Nov/14 ]

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

Comment by Marco Pivetta [ 17/Jan/15 ]

Handled in DDC-3387





[DDC-3152] Generating methods does not check for existing methods with different case Created: 04/Jun/14  Updated: 06/Jun/14  Resolved: 06/Jun/14

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Tools
Affects Version/s: 2.3.4
Fix Version/s: 2.5

Type: Bug Priority: Minor
Reporter: Jacob Walker Assignee: Marco Pivetta
Resolution: Fixed Votes: 0
Labels: orm


 Description   

When I use `orm:generate-entities --generate-methods=true` to add methods to an existing entity (such as when I add new properties) the generator will redeclare methods if my existing entity is using different case. This is a fatal error because PHP method names are treated as case insensitive.

I have not tested this in 2.4.

Here is a minimal example entity before running the generator. Not the case of `getID`

Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
/**
 * @ORM\Entity
 */
class Employee
{
    /**
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    public function getID()
    {
        return $this->id;
    }
}

And after running the generator

Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
/**
 * @ORM\Entity
 */
class Employee
{
    /**
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    public function getID()
    {
        return $this->id;
    }

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }
}


 Comments   
Comment by Steve Müller [ 05/Jun/14 ]

Hmm yeah it seems the EntityGenerator does not use reflection to determine whether a method/property already exists but instead tokenizes the source file and compares the methods/properties case-sensitive.
I will have a look at it.

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

Patch supplied in PR: https://github.com/doctrine/doctrine2/pull/1049

Comment by Jacob Walker [ 05/Jun/14 ]

Thanks for looking in to this so quickly, Steve.

Comment by Doctrine Bot [ 06/Jun/14 ]

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

Comment by Marco Pivetta [ 06/Jun/14 ]

Merged @ https://github.com/doctrine/doctrine2/commit/d71159c6c57bce5b83f9a2ddbb16ff5a289c30f1





[DDC-3141] Change the type of a column Created: 28/May/14  Updated: 28/May/14  Resolved: 28/May/14

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: DQL, ORM, Tools
Affects Version/s: 2.x
Fix Version/s: None

Type: Improvement Priority: Minor
Reporter: Mathias STRASSER Assignee: Marco Pivetta
Resolution: Won't Fix Votes: 0
Labels: postgresql
Environment:

All O.S.



 Description   

Is that possible to change the request when we would like to change the type of a column in PostgreSQL via Symfony 2 ?

app/console doctrine:schema:update --force

[Doctrine\DBAL\DBALException]
  An exception occurred while executing 'ALTER TABLE foo ALTER valid TYPE BOOLEAN':  

  SQLSTATE[42804]: Datatype mismatch: 7 ERROR:  column "valid" cannot be cast to type boolean

For resolve this problem I must execute manually this command :

ALTER TABLE foo ALTER valid TYPE BOOLEAN USING valid::BOOLEAN;

I've asked this question to DoctrineBundle, but they redirected to you (https://github.com/doctrine/DoctrineBundle/issues/292)



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

Mathias STRASSER does this happen also when data is not in the table?

To be honest, this exception seems valid to me, as it actually prevents you from applying destructive DDL on your schema.

Comment by Steve Müller [ 28/May/14 ]

I tend to agree with Marco Pivetta. I know of similar issues with other vendors, too and IMO this exception is perfectly valid as you would otherwise risk to loose data integrity. How would you expect a database to do data conversion between non-compatible types? Maybe you can force type conversion for some types but I don't think it is the task of DBAL to handle this. You should handle this manually IMO.

Comment by Mathias STRASSER [ 28/May/14 ]

I understand this prevent but I think if a user asked to apply a schema update, it should be applied or he should get prompted for a confirmation.
It think it's a pity we are forced to manually perform this query if we are sure.

What do you think ?

Comment by Steve Müller [ 28/May/14 ]

Mathias STRASSER I understand your concern. But this is an exception coming from the database server. How would you expect Doctrine to do the data conversion? Maybe in your case when converting to a BOOLEAN column, this could somehow work (even at database level). But how would you for example expect Doctrine to convert a STRING column to INTEGER for example. You just can't do that. Also you have to keep in mind that DBAL is an abstraction layer and thus requires a cross-vendor behaviour that is the same for all. It might be that PostgreSQL can force the conversion of any column type to BOOLEAN but other vendors can't do this natively. You could adopt the scenario to PHP and type casting. It's a similar scenario.

Comment by Marco Pivetta [ 28/May/14 ]

Won't be fixed.

As I've previously noted, this is an engine error that simply avoids a lossy conversion.

The conversion should be forced manually by the person running the schema tool (by manually running the dump command and applying the DDL statements)

Comment by Mathias STRASSER [ 28/May/14 ]

I quite understand.

Thanks for your replies.





[DDC-2829] Retrieve fieldName from PersistentCollection Created: 30/Nov/13  Updated: 02/Dec/13  Resolved: 02/Dec/13

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

Type: Improvement Priority: Minor
Reporter: Thomas Lallement Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: orm
Environment:

N/A



 Description   

Hi,

I use a custom listener based on the one of Knp DoctrineBehavior: https://github.com/KnpLabs/DoctrineBehaviors/blob/master/src/Knp/DoctrineBehaviors/ORM/Loggable/LoggableListener.php and I would like to use $uow->getScheduledCollectionDeletions() and $uow->getScheduledCollectionUpdates() to add the modifications from manyToMany relations. (like described here: https://groups.google.com/forum/#!topic/doctrine-user/ONDh5H4hMYQ).

So I itereate on the returned array to get a PersistentCollection from which I'm able to call:

$col->getOwner() : to retrieve the owning entity (the entity at the owning side of the association).

$col->getDeleteDiff() : to retrieve the entities that will be removed from the collection.

$col->getInsertDiff() : to retrieve the entities that will be added to the collection.

$col->getSnapshot() : to retrieve the last snapshot.

$col->toArray() : to retrieve the current entities in the collection.

That's good, and I can get all information about the association mapping but I can't retrieve the fieldName.

I think it could be easily added when initializing the PersistentCollection by adding fieldName in the $assoc parameter before to call setOwner() ?

See http://www.doctrine-project.org/api/orm/2.4/source-class-Doctrine.ORM.UnitOfWork.html#_computeChangeSet



 Comments   
Comment by Thomas Lallement [ 02/Dec/13 ]

In fact it's already possible by getting fieldName on after clling $col->getMapping();





[DDC-2730] Natural ordering in QueryBuilder Created: 09/Oct/13  Updated: 17/Oct/13  Resolved: 17/Oct/13

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

Type: Improvement Priority: Minor
Reporter: Sergio Pavón Salamanca Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: None


 Description   

Maybe this is not the best place to ask for a feature supported by doctrine. I apologize if I've chosen wrong channel.
Hi,
I can't find an easy way to do natural text ordering with QueryBuilder. OrderBy lets us order text, but I want to order including accents and other simbols. For instance, if we have this words:
Alabama, Boston, Álamo, Cardiff.
Natural order: Alabama, Álamo, Boston, Cardiff.
But current Doctrine order: Albama, Boston, Cardiff, Álamo.

I know that I can create a custom function or use native query, but I think that natural order often occurs. There are DBMS specific functions like TRANSLATE or REPLACE that can help, but I think that doctrine not support them.

Thank you,
Sergio.



 Comments   
Comment by Marco Pivetta [ 17/Oct/13 ]

This depends on the collation of your DB/Table/Column, not on Doctrine itself.





[DDC-2489] Missing semicolon in schema update tool, using dump-sql argument Created: 05/Jun/13  Updated: 08/Sep/13  Resolved: 08/Sep/13

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM, Tools
Affects Version/s: None
Fix Version/s: 2.4

Type: Bug Priority: Minor
Reporter: Robert-Jan Assignee: Guilherme Blanco
Resolution: Fixed Votes: 0
Labels: Cli, schematool


 Description   

When executing the schema-tool update script, using the --dump-sql argument (e.g. "app/console doctrine:schema:update --dump-sql" in a symfony2 project), the semicolon behind the last query is missing.



 Comments   
Comment by Guilherme Blanco [ 12/Jun/13 ]

Fixed in https://github.com/doctrine/doctrine2/commit/0d834d0bd4015de2c103a03592c1543399f1b363





[DDC-2465] ProxyClass load, and empty ids Created: 21/May/13  Updated: 22/May/13  Resolved: 21/May/13

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

Type: Improvement Priority: Minor
Reporter: Gabriele Tondi Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: None
Environment:

Osx



 Description   

If you have lazy association (example many-to-one) that have empty id (for empty i mean empty string and not null) you (correctly) get EntityNotFoundException.

But i'm working with a system that sometimes put an empty string instead of null in fk fields.

So i've add this little snipped of code __load method in $_proxyClassTemplate, ProxyFactory:

// GT, 2013-05-21 If all identifier are empty you not need to try load

        if (is_array($this->_identifier)) {
            $isEmpty = true;
            foreach($this->_identifier as $iK => $iV) {
                if (!empty($iV))
                    $isEmpty = false;
            }

            if ($isEmpty)
                return;
        }
        // END GT EDIT


 Comments   
Comment by Marco Pivetta [ 21/May/13 ]

What does `$this->_identifier` contain in your failing case?

Comment by Gabriele Tondi [ 21/May/13 ]

It contains for example

array(
[id] =>
);

Because on db you find an empty string and not a null value.

Comment by Marco Pivetta [ 21/May/13 ]

If I get it correctly, you are using empty strings to emulate NULL references, which is invalid in SQL ( I've explained it extensively at http://stackoverflow.com/questions/15502408/doctrine-2-use-default-0-values-instead-of-null-for-relation/15511715#15511715 )

Is this what you are doing? Because for any identifier that is not NULL an attempt to load it should be run, regardless of its content.

Comment by Gabriele Tondi [ 21/May/13 ]

That's not me

It's the system by which i'm sharing the db.
It uses MyIsam engine with no fk or index, so i've found this way to skip load when on db i've empty strings.

Are there other (maybe cleaner) ways?

Thanks,
Gabriele

Comment by Marco Pivetta [ 21/May/13 ]

No, the only correct way to handle this is to set NULL values for the association meta-columns. Marking as invalid

Comment by Gabriele Tondi [ 21/May/13 ]

I can't find doc about it: https://doctrine-orm.readthedocs.org/en/latest/reference/annotations-reference.html?highlight=column#annref-column

Can you give an example?

Comment by Marco Pivetta [ 21/May/13 ]

`$this->someAssociation = NULL;`. That's basically what I mean.

Comment by Gabriele Tondi [ 22/May/13 ]

Mmm, didn't understand.

Anyway, we've tried to fix the old Delphi Monster witch store empty strings instead of nulls... with no results.

So, here is my workaround, maybe this can be useful for other developers who will be in troubles in the future..

In "UnitOfWork" class, public method "createEntity".

[...]

UnitOfWork.php
 
// TODO: Is this even computed right in all cases of composite keys?
                    foreach ($assoc['targetToSourceKeyColumns'] as $targetColumn => $srcColumn) {
                        $joinColumnValue = isset($data[$srcColumn]) ? $data[$srcColumn] : null;

                        // START-EDIT

                        // GT: our moas store empty string instead of null in fk columns.
                        // So, let's check and handle it as null!

                        if (empty($joinColumnValue))
                            $joinColumnValue = null;

                        // END-EDIT

                        if ($joinColumnValue !== null) {
                            if ($targetClass->containsForeignIdentifier) {
                                $associatedId[$targetClass->getFieldForColumn($targetColumn)] = $joinColumnValue;
                            } else {
                                $associatedId[$targetClass->fieldNames[$targetColumn]] = $joinColumnValue;
                            }
                        }
                    }

[...]

Regards,
Gabriele

Comment by Marco Pivetta [ 22/May/13 ]

Gabriele Tondi the ORM does not deal with such architectures (nor with generally invalid usage of RDBMS systems). The only acceptable solution in ORM is with correct NULL values, as it should be, so this patch is invalid.





[DDC-2407] AbstractExporter _getIdGeneratorTypeString does not know about the UUID generator Created: 20/Apr/13  Updated: 20/Apr/13  Resolved: 20/Apr/13

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Tools
Affects Version/s: 2.3.3
Fix Version/s: 2.4

Type: Bug Priority: Minor
Reporter: Jeroen Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: None


 Description   

Shouldn't the AbstractExporter->_getIdGeneratorTypeString() method also know about the UUID generator ?



 Comments   
Comment by Benjamin Eberlei [ 20/Apr/13 ]

Fixed for 2.4





[DDC-2388] Zend Optimizer Plus/opcache have overlap in config settings, annotations reader doesn't identify these properly Created: 04/Apr/13  Updated: 08/Sep/13  Resolved: 20/Apr/13

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers
Affects Version/s: 2.3.3
Fix Version/s: 2.4

Type: Bug Priority: Minor
Reporter: Ross Cousens Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: None


 Description   

Doctrine\Common\Annotations\AnnotationReader.php

A change was recently authored in the AnnotationReader constructor that checked for a properly configured opcode cache (namely saving comments so that Doctrine can parse annotations).

The current open source version of Zend Optimizer+ hosted at GitHub (https://github.com/zend-dev/ZendOptimizerPlus) when loaded registers itself as a module with the name "Zend Optimizer+" but takes configuration directives in the form of "opcache.<parameter>".

The change to the constructor requires that if the module name is Zend Optimizer+, then the configuration directives must be prefixed with "zend_optimizerplus.<parameter>". This is clearly incorrect.

The most recent update now complains of an AnnotationException as a consequence of this change when running Symfony2 (or Doctrine) with the latest opcache because configuration directives aren't detected properly.

I am happy to fix this but could not find a way to report an issue to initiate the process.

I would suggest something like this in the constructor:

if ((extension_loaded('Zend Optimizer+') || extension_loaded('opcache')) && !(ini_get('opcache.save_comments') == 0 XOR ini_get('zend_optimizerplus.save_comments') == 0)) {

What this means is that if either extension is loaded, one of those directives must be true and configured. This is a compromise. The alternative would be to keep the original source and do the following:

if (extension_loaded('Zend Optimizer+') && ini_get('zend_optimizerplus.save_comments') == 0) {
if (ini_get('opcache.save_comments') == 0)

{ throw AnnotationException::optimizerPlusSaveComments(); }

}

if (extension_loaded('opcache') && ini_get('opcache.save_comments') == 0)

{ throw AnnotationException::optimizerPlusSaveComments(); }

I have no idea about the "opcache" module and what it actually equates to or whether it has alternative formats for its configuration directives. I feel like the second suggestion is even smellier than my original suggestion despite probably handling the edge case better.

If you want a pull request, I will send one, just let me know how you want to handle it.

If my PHP is horrible I apologise.



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

Ross Cousens is this already enstabilished? It's not worth changing it until the ZO+ stuff is stable.

Comment by Ross Cousens [ 15/Apr/13 ]

Marco Pivetta Benjamin Eberlei

Seems stable to me.

I guess whether this is a priority or not depends on your subjective weighting of its importance and whether or not you use ZO+. I've ditched APC, and moved 20+ web servers over to Apache+ZO+. I currently deploy my own version of DBAL commons because it is not possible to work around it.

https://github.com/zend-dev/ZendOptimizerPlus

Please see this reference, why would they suddenly change the name of all the configuration directives especially in light of the fact that this is being integrated into PHP 5.5 as the standard generic "opcache" solution? I think this is where the confusion comes from. It might be branded as ZO+ on Github, but that becomes irrelevant when it's part of core.

I've tried contacting Beberlei directly (the author of the change), on Twitter and via e-mail, but no response. Not getting any response is quite annoying as it's been a month since this change was made and whenever I update an existing site or publish a new site I have to deal with this.

I need to invest some time in finding out how I can maintain my own fork of OSS projects that pull changes in from the branched master but allow me to keep 1 or 2 files totally different. The other thing that drives me insane is the fact that the postgresql platform drivers can't implement GUID generators because it requires an extension be enabled on the server (seriously, solve with documentation, it's easy to detect programmatically as well) plus the choosing of a function, when there is obviously only one sane choice.

I am so grateful for the opportunity to develop with OSS, but the bureaucratic decision-by-committee stuff is so frustrating when you're an end-user and can't find anyone who gives half a crap about stuff that is just plain stupid but overlooked due to resources already spread thin or whatever may be the case. I would be happy to develop fixes as well, but when they languish because you can't find a maintainer that is familiar with the issue, interested in finding a fix, and has the time available to act as custodian of a pull request, it is incredibly demoralizing.

Comment by Benjamin Eberlei [ 20/Apr/13 ]

Fixed and released a Collections 1.1.1 version

Comment by Ross Cousens [ 23/Apr/13 ]

Thanks Benjamin, I am grateful for the fix! Happy coding!





[DDC-2345] convertObjectParameterToScalarValue() raises a notice Created: 12/Mar/13  Updated: 01/May/13  Resolved: 01/May/13

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.3
Fix Version/s: 2.4

Type: Bug Priority: Minor
Reporter: Massimiliano Arione Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: None


 Description   

In Doctrine\ORM\AbstractQuery.php, the method convertObjectParameterToScalarValue() can raise a Notice.
This code:

$value = $values[$class->getSingleIdentifierFieldName()];

should be changed in this one:

if (isset($values[$class->getSingleIdentifierFieldName()])) {
    $value = $values[$class->getSingleIdentifierFieldName()];
}


 Comments   
Comment by Marco Pivetta [ 12/Mar/13 ]

Massimiliano Arione the current DQL implementation doesn't allow you to bind composite key identifiers as parameters, thus you will never reach that piece of code.

A test would be needed for this case.

Comment by Massimiliano Arione [ 12/Mar/13 ]

Unfortunately, I'm not really a Doctrine guru.
I can tell you that I'm getting that notice, using Sortable behavior with Symfony2.
This is a partial error stack:

1 in (...)/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php at line 282

2 at ErrorHandler ->handle ('8', 'Undefined index: id', '(...)/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php', '282', array('value' => object(MyEntity), 'class' => object(ClassMetadata), 'values' => array()))

3 in (...)/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php at line 282
at AbstractQuery ->convertObjectParameterToScalarValue (object(MyEntity))

4 in (...)/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php at line 260
at AbstractQuery ->processParameterValue (object(MyEntity))

5 in (...)/vendor/doctrine/orm/lib/Doctrine/ORM/Query.php at line 285
at Query ->processParameterMappings (array('group__1' => array('0')))

6 in (...)/vendor/doctrine/orm/lib/Doctrine/ORM/Query.php at line 258
at Query ->_doExecute ()

7 in (...)/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php at line 737
at AbstractQuery ->execute (null, '1')

8 in (...)/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php at line 538
at AbstractQuery ->getResult ()

9 in (...)/vendor/gedmo/doctrine-extensions/lib/Gedmo/Sortable/SortableListener.php at line 410
at SortableListener ->getMaxPosition (object(EntityManager), object(ClassMetadata), array('position' => 'rank', 'groups' => array('my_entity'), 'useObjectClass' => 'Meeting\GestioneBundle\Entity\MyRelatedEntity'), object(MyRelatedEntity))

10 in (...)/vendor/gedmo/doctrine-extensions/lib/Gedmo/Sortable/SortableListener.php at line 114
at SortableListener ->prePersist (object(LifecycleEventArgs))

11 in (...)/vendor/symfony/symfony/src/Symfony/Bridge/Doctrine/ContainerAwareEventManager.php at line 61
Comment by Marco Pivetta [ 12/Mar/13 ]

Massimiliano Arione having a composite primary key?

Comment by Massimiliano Arione [ 12/Mar/13 ]

Nope, just a plain "id".

Comment by Benjamin Eberlei [ 01/May/13 ]

Fixed in 2.4





[DDC-2176] Illegal offset type in isset or empty in UnitOfWork Created: 28/Nov/12  Updated: 15/Feb/14  Resolved: 01/May/13

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.3, 2.4
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: Yves Berkholz Assignee: Benjamin Eberlei
Resolution: Duplicate Votes: 0
Labels: unitofwork

Issue Links:
Duplicate
duplicates DDC-1998 Problem when deleting with EntityMana... Resolved

 Description   

Steps to reproduce the problem?

  • A custom DBAL type, that extends a scalar build-in type e.g. DBAL\Types\StringType
  • convertToPHPValue of custom DBAL type returns an instance of a class (implements __toString method)
  • Custom DBAL type is used as primary key in an entity
  • initially persist entity and flush entity manager
  • modify entity (keep same primary key) and persist entity again causes:

    Warning: Illegal offset type in isset or empty in vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 2407

I guess the solution in Doctrine\ORM\Internal\Hydration namespace by explicit converting result of convertToPHPValue if result is not a scalar value.



 Comments   
Comment by Marco Pivetta [ 23/Jan/13 ]

This one will introduce way too much overhead. We don't really support identifiers that are custom object types.

What is the exact version of the ORM? I couldn't spot anything at line 2407.

Comment by Yves Berkholz [ 24/Jan/13 ]

I use a dev branch and updated the version since creation of the report, hence the line number changed to 2466.

UnitOfWork.php
} else {
	$entity = $this->newInstance($class);
	$oid    = spl_object_hash($entity);

	$this->entityIdentifiers[$oid]  = $id;
	$this->entityStates[$oid]       = self::STATE_MANAGED;
	$this->originalEntityData[$oid] = $data;

	$this->identityMap[$class->rootEntityName][$idHash] = $entity; // <- 2466

	if ($entity instanceof NotifyPropertyChanged) {
		$entity->addPropertyChangedListener($this);
	}

	$overrideLocalValues = true;
}

Ok, I understand the overhead problem. I only tried to create a custom enum type that is represented by a class.
But i solved this by converting the value within the getter/setter of entity class.
It would have been nice to do this in the DBAL type, but it works that way.
Therefore, you might close the report or move it on a far future version "wishlist".
Anyway, thank for your time.

Nevertheless the information you requested:
Composer: doctrine/orm [2.3.x-dev fdd0af3]
git reference: fdd0af34e6fced967b8751bc3e4792c11ef86d57

Additionally, exception trace might help

 
() at D:/projects/{projectname}/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:2466
 Symfony/Component/HttpKernel/Debug/ErrorHandler->handle() at D:/projects/{projectname}/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:2466
 Doctrine/ORM/UnitOfWork->createEntity() at D:/projects/{projectname}/vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/SimpleObjectHydrator.php:135
 Doctrine/ORM/Internal/Hydration/SimpleObjectHydrator->hydrateRowData() at D:/projects/{projectname}/vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/SimpleObjectHydrator.php:50
 Doctrine/ORM/Internal/Hydration/SimpleObjectHydrator->hydrateAllData() at D:/projects/{projectname}/vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php:111
 Doctrine/ORM/Internal/Hydration/AbstractHydrator->hydrateAll() at D:/projects/{projectname}/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php:678
 Doctrine/ORM/Persisters/BasicEntityPersister->load() at D:/projects/{projectname}/vendor/doctrine/orm/lib/Doctrine/ORM/EntityRepository.php:171
 Doctrine/ORM/EntityRepository->findOneBy() at D:/projects/{projectname}/vendor/doctrine/orm/lib/Doctrine/ORM/EntityRepository.php:211
 Doctrine/ORM/EntityRepository->__call() at D:/projects/{projectname}/vendor/{customvendor}/lib-doctrine/src/{VendorNs}/Lib/Doctrine/DataFixtures/AbstractBaseFixture.php:123
 {VendorNs}/Lib/Doctrine/ORM/Repository/BaseLookupRepository->findOneById() at D:/projects/{projectname}/vendor/{customvendor}/lib-doctrine/src/{VendorNs}/Lib/Doctrine/DataFixtures/AbstractBaseFixture.php:123
 {VendorNs}/Lib/Doctrine/DataFixtures/AbstractBaseFixture->findPersistedEntity() at D:/projects/{projectname}/src/ProjectVendor/Bundle/DataFixturesBundle/Classes/ORM/LookupFixture.php:38
 {ProjectNs}/Bundle/DataFixturesBundle/Classes/ORM/LookupFixture->lookupentityDefaultBuilder() at D:/projects/{projectname}/src/ProjectVendor/Bundle/DataFixturesBundle/DataFixtures/ORM/Main/User/LookupData.php:59
 {ProjectNs}/Bundle/DataFixturesBundle/DataFixtures/ORM/Main/User/LookupData->onlinestatusBuild() at n/a:n/a
 call_user_func() at D:/projects/{projectname}/src/ProjectVendor/Bundle/DataFixturesBundle/Classes/ORM/LookupFixture.php:78
 {ProjectNs}/Bundle/DataFixturesBundle/Classes/ORM/LookupFixture->lookupentityDefaultLoader() at D:/projects/{projectname}/src/ProjectVendor/Bundle/DataFixturesBundle/DataFixtures/ORM/Main/User/LookupData.php:42
 {ProjectNs}/Bundle/DataFixturesBundle/DataFixtures/ORM/Main/User/LookupData->load() at D:/projects/{projectname}/vendor/doctrine/data-fixtures/lib/Doctrine/Common/DataFixtures/Executor/AbstractExecutor.php:120
 Doctrine/Common/DataFixtures/Executor/AbstractExecutor->load() at D:/projects/{projectname}/vendor/doctrine/data-fixtures/lib/Doctrine/Common/DataFixtures/Executor/ORMExecutor.php:83
 Doctrine/Common/DataFixtures/Executor/ORMExecutor->Doctrine/Common/DataFixtures/Executor/{closure}() at n/a:n/a
 call_user_func() at D:/projects/{projectname}/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:223
 Doctrine/ORM/EntityManager->transactional() at D:/projects/{projectname}/var/cache/apps/web/local/jms_diextra/doctrine/EntityManager_50ffafed6b09f.php:31
 EntityManager50ffafed6b09f_546a8d27f194334ee012bfe64f629947b07e4919/__CG__/Doctrine/ORM/EntityManager->transactional() at D:/projects/{projectname}/vendor/doctrine/data-fixtures/lib/Doctrine/Common/DataFixtures/Executor/ORMExecutor.php:85
 Doctrine/Common/DataFixtures/Executor/ORMExecutor->execute() at D:/projects/{projectname}/vendor/doctrine/doctrine-fixtures-bundle/Doctrine/Bundle/FixturesBundle/Command/LoadDataFixturesDoctrineCommand.php:106
 Doctrine/Bundle/FixturesBundle/Command/LoadDataFixturesDoctrineCommand->execute() at D:/projects/{projectname}/vendor/symfony/symfony/src/Symfony/Component/Console/Command/Command.php:238
 Symfony/Component/Console/Command/Command->run() at D:/projects/{projectname}/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:192
 Symfony/Component/Console/Application->doRun() at D:/projects/{projectname}/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php:78
 Symfony/Bundle/FrameworkBundle/Console/Application->doRun() at D:/projects/{projectname}/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:105
 Symfony/Component/Console/Application->run() at D:/projects/{projectname}/bin/console.php:17
Comment by Benjamin Eberlei [ 01/May/13 ]

This works in this recent commit here, 0864ab8adac5c31d5ba97f0eb6792e5431a75b70. Should have worked before as well. Can you verify?

Comment by Benjamin Eberlei [ 01/May/13 ]

Related to DDC-1998, tests this behavior

Comment by Boy Baukema [ 28/Aug/13 ]

I'm still getting this issue, even after upgrading to 2.4.0-RC2.

Comment by Marco Pivetta [ 28/Aug/13 ]

Just a note: this is broken since 2.4 because before 2.4 we didn't convert meta fields via DBAL types. If your identifier is an object this will probably be the problem. We could cast it to string though.





[DDC-2136] convert-mapping can't create YML from Annotation when Id column is a OneToOne relationship Created: 11/Nov/12  Updated: 01/May/13  Resolved: 01/May/13

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.3
Fix Version/s: 2.4

Type: Bug Priority: Minor
Reporter: Gergely Polonkai Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: yaml
Environment:

Symfony 2.1.3



 Description   

I have two entities

/**

  • @ORM\Entity
    */
    class User {
    /**
  • @ORM\Id
  • @ORM\GeneratedValue(strategy="AUTO")
  • @ORM\Column(type="integer")
    */
    private $id
    }

/**

  • @ORM\Entity
    */
    class UserData {
    /**
  • @ORM\Id
  • @ORM\OneToOne(targetEntity="User")
    */
    private $id
    }

When I convert these with symfony's

doctrine:mapping:convert yml test/

it generates an entity definition for UserData without any id fields, which, of course, cannot be imported to the database, as the new entity doesn't have an identifier column.



 Comments   
Comment by Benjamin Eberlei [ 01/May/13 ]

Fixed in 2.4





[DDC-2121] EntityGenerator generates bad type hint (missing \) Created: 04/Nov/12  Updated: 09/Nov/12  Resolved: 06/Nov/12

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Tools
Affects Version/s: 2.1, 2.2, 2.3
Fix Version/s: 2.3.1

Type: Bug Priority: Minor
Reporter: Stéphane Erard Assignee: Fabio B. Silva
Resolution: Fixed Votes: 0
Labels: None


 Description   

Having an Entity class with this property declaration :

/**
 * @ORM\OneToMany(targetEntity="Plan", mappedBy="Dossier")
 * @var Plan[]
 **/
protected $Plans;

Getter & Setter are generated this way :

/**
 * Add Plans
 *
 * @param se\JpsBundle\Entity\Plan $plans
 * @return Dossier
 */
public function addPlan(\se\JpsBundle\Entity\Plan $plans)
{
  $this->Plans[] = $plans;
  return $this;
}

Problem lies in the

@param se\JpsBundle\Entity\Plan $plans

Should be :

\se\JpsBundle\Entity\Plan $plans

Same thing for Doctrine Collection class.



 Comments   
Comment by Fabio B. Silva [ 06/Nov/12 ]

Fixed : https://github.com/doctrine/doctrine2/commit/262c3eea6bd4313d34558ff434bf9b8ff34b7ab3





[DDC-2112] cascade remove revert order Created: 01/Nov/12  Updated: 08/Nov/12  Resolved: 08/Nov/12

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

Type: Bug Priority: Minor
Reporter: Ivan Borzenkov Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None

Attachments: Text File DDC2112.patch    

 Description   

cascadeRemove incorrect work

UnitOfWork

in commit() (336)

// Entity deletions come last and need to be in reverse commit order
if ($this->entityDeletions) {
for ($count = count($commitOrder), $i = $count - 1; $i >= 0; --$i)

{ $this->executeDeletions($commitOrder[$i]); }

}

----------------------------------------------------------------
in doRemove (1630)

// Cascade first, because scheduleForDelete() removes the entity from the identity map, which
// can cause problems when a lazy proxy has to be initialized for the cascade operation.
$this->cascadeRemove($entity, $visited);

......

$this->scheduleForDelete($entity);

in array we get

child
child
parent

revert in commit - first remove parent and get foregein key error

if move cascadeRemove after switch all woork correct



 Comments   
Comment by Ivan Borzenkov [ 01/Nov/12 ]

patch

Comment by Ivan Borzenkov [ 01/Nov/12 ]
class Domain
{
...
    /**
     * @ORM\OneToMany(targetEntity="Query", mappedBy="domain", cascade={"all"})
     */
    protected $q;
...
}

class Query
{
...
    /**
     * @ORM\ManyToOne(targetEntity="Domain", inversedBy="q")
     */
    protected $domain;
...
}

if remove Domain - get mysql error foreign key





[DDC-2019] addOrderBy function incomplete Created: 07/Sep/12  Updated: 09/Feb/13  Resolved: 09/Feb/13

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.2.3
Fix Version/s: 2.4

Type: Bug Priority: Minor
Reporter: Jérôme Forêt Assignee: Alexander
Resolution: Fixed Votes: 0
Labels: None