[DDC-3640] Force version increment via mapped property Created: 26/Mar/15  Updated: 26/Mar/15

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

Type: Improvement Priority: Minor
Reporter: Darien Hager Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: mapping, orm

Issue Links:
Reference
relates to DDC-2864 New type of lock: OPTIMISTIC_FORCE_IN... Open
relates to DDC-1507 State change detection for version in... Open

 Description   

Existing feature:

It is currently possible to use optimist-locking against an entity through a version code or timestamp, which becomes incremented when the entity changes. Unfortunately, there is no way for an entity to signal that its version should be incremented when no (direct) changes have occurred.

Problem:

Sometimes you want to control or gate wide-spread or indirect changes via a particular entity, such as the root of a tree of other mutable entities. This is particularly common in Domain Driven Design.

Proposal:

Create a new configuration option for a PHP property that identifies it as a "version incrementor flag". It is only legal on entities that also have a version-field. This field will always be set to false when an entity is hydrated.

When entities are being checked for changes and flushed, this flag will (if it evaluates to true) force the version-field to update. Note that if the entity has "real changes", it will be saved and the version-field will update regardless. At the end of this process, the field is reset back to false.

This allows the user to write code such as:

Entity example

    /** @Version @Column(type="integer") */
    private $version;

    /** @VersionIncrementFlag */
    $changed = false;

    /** @OneToMany(targetEntity="Child", mappedBy="parent") */
    private $children;    

    public function zeroChildren(){
        foreach($this->children as $child){
            $child->setValue(0);
        }
        $this->changed = true; // Where $changed is the incrementor flag
    }    

Issues with other approaches:

The current workaround of a "junk column" is... suboptimal. It requires a junk data column in the database, and its presence does not easily capture the intent of the user. It also leads to extra database operations, since the junk data has to be saved no matter what.

Adding a specialized method to EntityManager, like with $em->touchVersion($entity); is also problematic, since it means you cannot conveniently trigger the new behavior when deep inside the object-graph.



 Comments   
Comment by Darien Hager [ 26/Mar/15 ]

I'm willing to try implementing this if folks feel it could get included.





[DDC-1507] State change detection for version incrementation (for optimistic locking) in combination with orphanRemoval Created: 23/Nov/11  Updated: 26/Mar/15

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

Type: Improvement Priority: Major
Reporter: Georg Wächter Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: unitofwork, versioned

Issue Links:
Reference
is referenced by DDC-2864 New type of lock: OPTIMISTIC_FORCE_IN... Open
is referenced by DDC-3640 Force version increment via mapped pr... Open

 Description   

As i understand the documentation correctly, orphanRemoval associations have the meaning of a "part of" relationship. In the example (http://www.doctrine-project.org/docs/orm/2.0/en/reference/working-with-associations.html#orphan-removal) the adresses are part of the contact.

In my opinion we should reason that the state of the adress consists of the states of all nested contacts. As a consequence we should flag the contact as "dirty" when the adresses change.

This is relevant for optimistic locking scenarios or event handlers. In my application i tried to use optimistic locking for "contacts", which does not work if i don't change anything in the contact but only in the nested addresses.



 Comments   
Comment by Benjamin Eberlei [ 27/Nov/11 ]

This is still only an approvement, you can workaround this and handle is in your domain code.

Comment by Georg Wächter [ 27/Nov/11 ]

Not in all cases. The first problem is that my domain code can't modify the version property, doctrine seems to block any manipulations to it. So i'm not able to increment the variable myself.

The only solution is to implement optimistic locking on my own or to add a dummy persistent boolean field that gets inversed by my domain code .. which would trigger the doctrine implementation for the optimistic locking.

I think it's clear that the second option shouldn't be a choice. If doctrine doesn't handle the overall case exactly it should allow me to increment the version number myself.

Comment by Darien Hager [ 26/Mar/15 ]

Bump: I'm having a similar issue. Essentially I want to force the entity's version to be updated, even if there aren't any other "real" changes to go with it.

One idea for a workaround: Since version fields can only be integers or timestamps, define a "clearly wrong" magic value like "FORCE_INCREMENT". This would allow objects to signal without needing a reference to the EntityManager.

Would folks be open to a pull-request over this?





[DDC-2864] New type of lock: OPTIMISTIC_FORCE_INCREMENT Created: 18/Dec/13  Updated: 26/Mar/15

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

Type: New Feature Priority: Minor
Reporter: Szurovecz János Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None

Issue Links:
Reference
relates to DDC-1507 State change detection for version in... Open
is referenced by DDC-3640 Force version increment via mapped pr... Open

 Description   

When optimistick locking is being used, the version field is incremented after the update only if the entity itself has been modified. In Domain-Driven Design another kind of locking mechanism is essential: OPTIMISTIC_FORCE_INCREMENT. It means that the version field is always incremented after an update. The lack of this feaure can be realized when only the aggregate root has a version field and some other parts of the aggregate is being modified.

PESSIMISTIC_FORCE_INCREMENT is also an interesting lock type which might be useful as well.



 Comments   
Comment by Darien Hager [ 26/Mar/15 ]

I'm having this same issue, although I'm not certain a new locking-type is the answer.

Basically, I want to ensure that an entity gets updated with a new version integer/timestamp, whether or not anything "real" has been changed on it. It seems the only workaround is to designate a "junk" property and change that, which isn't particularly elegant.

The problem with a locking-type is that individual entities can't signal that they need incrementing without having a reference to the entity-manager so that they can $em->lock() .





[DDC-3639] [GH-1349] Fix #1347 Created: 26/Mar/15  Updated: 26/Mar/15

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

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


 Description   

This issue is created automatically through a Github pull request on behalf of zeroedin-bill:

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

Message:

This PR fixes #1347.






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

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

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

Attachments: File DDC3184Test.php    

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

In master branch all works perfect

Comment by Dmitry Korotovsky [ 23/Jun/14 ]

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

Comment by Marco Pivetta [ 23/Jun/14 ]

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

Comment by Dmitry Korotovsky [ 23/Jun/14 ]

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

Comment by Marco Pivetta [ 23/Jun/14 ]

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





[DDC-3515] [GH-1263] #1223 DDC-3453 - make `EntityManager` constructor `public` Created: 18/Jan/15  Updated: 25/Mar/15

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

Type: Improvement Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: constructor, entitymanager, setup

Issue Links:
Reference
is referenced by DDC-3453 [GH-1223] Refactored construction of ... Resolved

 Description   

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

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

Message:



 Comments   
Comment by Doctrine Bot [ 18/Jan/15 ]

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

Comment by Doctrine Bot [ 18/Jan/15 ]

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

Comment by Doctrine Bot [ 18/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-1283] Possible issue with PersistentCollection#getDelete/InsertDiff() Created: 21/Jul/11  Updated: 25/Mar/15

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

Type: Improvement Priority: Minor
Reporter: Glen Ainscow Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Using the following code, when you go from (1, 2) to (1), (2) is deleted as expected. However, if you go from (1, 2) to (2), (1) and (2) are deleted and (2) is then inserted. Is this the desired behaviour? (i.e. 2 extra queries)

$bracket->getTournamentLocations()->takeSnapshot();

$col = $bracket->getTournamentLocations()->unwrap();

$col->clear();

foreach ($form->getValue('tournamentLocations') as $id) {
    $col->add($em->getReference('Tournaments_Model_TournamentLocation', $id));
}

$bracket->getTournamentLocations()->setDirty(true);


 Comments   
Comment by Benjamin Eberlei [ 26/Jul/11 ]

First, you are using internal API therefore you are on your own anyways.

This is marked as improvment now, the functionality works, it may just be inefficient.

Comment by Guilherme Blanco [ 09/Dec/11 ]

Hi,

I'm marking issue as invalid because you're conceptually wrong.
What you're trying to do is telling that a collection of new entities is holded by a collection of Persistent entities.
The reference internally of PersistentCollection to ArrayCollection means a lot here.

Correct code would be you to regenerate the collection (a new ArrayCollection) and just assign it to setTournamentLocations($newCollection);

Does this explanation is enough for you?

Cheers,

Comment by Glen Ainscow [ 23/Dec/11 ]

Hi Guilherme,

If I do this:

$locations = new ArrayCollection();

foreach ($form->getValue('tournamentLocations') as $id) {
    $locations->add($em->getReference('Tournaments_Model_TournamentLocation', $id));
}

$bracket->setTournamentLocations($locations);

... then all the records are deleted, before adding the new records. This is inefficient and causes extra, unnecessary write operations.

Can't Doctrine perform diffs when persisting the collection, so that only the necessary deletes and inserts are executed?

Comment by Guilherme Blanco [ 13/Jan/12 ]

We could add it, but I don't think it worth the effort.
Main problem with this one is that we use C-level binary comparison to get the diff. That's what you entities/hash pointers are different.
We would have to write our own diff-comparator for both collections, which would probably slowdown the entire Doctrine.

I'd rather consider that it's not possible to be done at the moment, but I need much more investigation for that. This will be something that I'll probably only do when I look at this issue again with a lot of time (which is really hard to happen).

If you have some spare time, feel free to make some attempts.
Just don't forget to enable performance tests in Doctrine Unit Test suite.





[DDC-3637] [GH-1347] problem with LimitSubqueryOutputWalker when use InheritanceType Created: 25/Mar/15  Updated: 25/Mar/15

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

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


 Description   

This issue is created automatically through a Github pull request on behalf of alexander-orabey:

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

Message:

When we use InheritanceType ("SINGLE_TABLE") catch exception that field in joined class does not exist in base class.



 Comments   
Comment by Doctrine Bot [ 25/Mar/15 ]

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





[DDC-3635] QueryBuilder - INSTANCE OF with parameter not working Created: 24/Mar/15  Updated: 25/Mar/15

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

Type: Bug Priority: Major
Reporter: Wouter Wiltenburg Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: binding, dql, parameter
Environment:

Zend Framework 2



 Description   

I use single table class inheritance.
When I write my INSTANCE OF clause in my QueryBuilder like this:

    $result = $this->createQueryBuilder('o')
        ->leftJoin('o.child', 'c')
        ->where('c INSTANCE OF :entity_class')
        ->setParameter('entity_class', 'My\Entity\Class')
        ->getQuery()
        ->getResult();

It does not work correctly. The problem seems to lie in the fact that the parameter is bound to the SQL query. So if I change the entity_class to the discriminator column name it works correctly.

So if the discriminator value for My\Entity\Class would be discriminator then this does work:

    $result = $this->createQueryBuilder('o')
        ->leftJoin('o.child', 'c')
        ->where('c INSTANCE OF :entity_class')
        ->setParameter('entity_class', 'discriminator')
        ->getQuery()
        ->getResult();

So the step for getting the discriminator column from the class name is missing and instead the class name is bound to the MySql query directly.






[DDC-2290] Infer custom Types from the field for query parameters Created: 08/Feb/13  Updated: 25/Mar/15

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

Type: Improvement Priority: Major
Reporter: Matthieu Napoli Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 3
Labels: None


 Description   

When using a mapping Type that declares convertToDatabaseValue, the method is not always called in queries.

Example:

SELECT ... WHERE entity.field = ?1

(with entity.field being of custom type 'the_mapping_type')

Type::convertToDatabaseValue() is correctly called when using:

$query->setParameter('1', 'foo', 'the_mapping_type');

But it is not called when using:

$query->setParameter('1', 'foo');

which gives a query that returns invalid results.

Like other mapping types in this situation, there is no reason the type is not inferred automatically from the field.

I have written a failing test case in Doctrine\Tests\ORM\Functional\TypeValueSqlTest:

    public function testQueryParameterWithoutType()
    {
        $entity = new CustomTypeUpperCase();
        $entity->lowerCaseString = 'foo';

        $this->_em->persist($entity);
        $this->_em->flush();

        $id = $entity->id;

        $this->_em->clear();

        $query = $this->_em->createQuery('SELECT c.id from Doctrine\Tests\Models\CustomType\CustomTypeUpperCase c where c.lowerCaseString = ?1');
        $query->setParameter('1', 'foo');

        $result = $query->getResult();

        $this->assertCount(1, $result);
        $this->assertEquals($id, $result[0]['id']);
    }


 Comments   
Comment by Matthieu Napoli [ 08/Feb/13 ]

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

Comment by Matthieu Napoli [ 08/Feb/13 ]

The test is in this branch: https://github.com/myc-sense/doctrine2/tree/DDC-2290

Comment by Matthieu Napoli [ 29/Oct/13 ]

The organization name has changed so the previous URL is a 404.

Here is the branch containing the failing testcase: https://github.com/myclabs/doctrine2/tree/DDC-2290

Comment by Benjamin Morel [ 28/Jan/14 ]

Any news on this one? Also, I just noticed that it does not cover the original problem I've reported in DDC-2224: I was specifically talking about convertToDatabaseValueSQL() and not convertToDatabaseValue().
My problem is that even when passing the third parameter $type, it does not use the conversion function from convertToDatabaseValueSQL().

Should we reopen DDC-2224?

Comment by Doctrine Bot [ 23/Mar/15 ]

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

Comment by Doctrine Bot [ 25/Mar/15 ]

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

Comment by Doctrine Bot [ 25/Mar/15 ]

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





[DDC-1825] generate entities with traits Created: 18/May/12  Updated: 24/Mar/15

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

Type: Improvement Priority: Major
Reporter: Matthias Breddin Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 6
Labels: None
Environment:

php 5.4.3, symfony2.1-dev
php 5.5.12, symfony 2.5



 Description   

When a trait with included setters and getters is used and generate entities is called, doctrine add another set of getters and setters to the "main" entity where the trait is used.



 Comments   
Comment by Martin Aarhof [ 01/May/14 ]
/**
 * @ORM\Entity
 */
class Product {
    use Traits\Created;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

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

    /**
     * Set name
     *
     * @param string $name
     * @return Attribute
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string 
     */
    public function getName()
    {
        return $this->name;
    }

}
Trait Created {
    /**
     * @var \DateTime $created
     *
     * @Gedmo\Timestampable(on="create")
     * @ORM\Column(type="datetime")
     */
    private $created;

    /**
     * @return \DateTime
     */
    public function getCreated()
    {
        return $this->created;
    }
}

Now when I run php app/console doctrine:generate:entities it copies everything from the trait and into the entity, so the entity now looks like

/**
 * @ORM\Entity
 */
class Product {
    use Traits\Created;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

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

    /**
     * Set name
     *
     * @param string $name
     * @return Attribute
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string 
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @var \DateTime $created
     *
     * @Gedmo\Timestampable(on="create")
     * @ORM\Column(type="datetime")
     */
    private $created;

    /**
     * @return \DateTime
     */
    public function getCreated()
    {
        return $this->created;
    }

}

And ofcourse invalidates the entity because it now has two methods of the getCreated and two of private $created

Comment by Wilgert Velinga [ 01/Dec/14 ]

Unfortunately I am also suffering from this bug. Is there anything I can do to help resolve it?

Comment by Ludwig Ruderstaller [ 24/Mar/15 ]

Same here - i think an easy fix would be to introduce an additional parameter, which if set, ignores all traits.





[DDC-3633] Schema creation problem on PostgreSQL Created: 22/Mar/15  Updated: 22/Mar/15

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

Type: Bug Priority: Major
Reporter: Dmitry Korotovsky Assignee: Steve Müller
Resolution: Unresolved Votes: 0
Labels: schematool


 Description   

Schema tool can't create correct schema on empty database in PostgreSQL:

$ php app/console doctrine:schema:create --env=test
ATTENTION: This operation should not be executed in a production environment.

Creating database schema...

[Doctrine\ORM\Tools\ToolsException]
Schema-Tool failed with Error 'An exception occurred while executing 'CREATE SCHEMA public':
SQLSTATE[42P06]: Duplicate schema: 7 ERROR: schema "public" already exists' while executing DDL: CREATE SCHEMA public






[DDC-3561] Wrong SQL generated for Drop Foreign Key on MySQL Created: 06/Feb/15  Updated: 20/Mar/15

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

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

operating system: osx yosemite
database driver: pdo_mysql
installed bundles:
doctrine/annotations v1.2.3
doctrine/cache v1.4.0
doctrine/collections v1.2
doctrine/common v2.4.2
doctrine/data-fixtures dev-master ac36ccc
doctrine/dbal v2.5.1
doctrine/doctrine-bundle v1.3.0
doctrine/doctrine-cache-bundle v1.0.1
doctrine/doctrine-fixtures-bundle v2.2.0
doctrine/doctrine-migrations-bundle dev-master 81575a4
doctrine/inflector v1.0.1
doctrine/instantiator 1.0.4
doctrine/lexer v1.0.1
doctrine/migrations dev-master 96f838b
doctrine/mongodb 1.1.6
doctrine/mongodb-odm dev-master 23152aa
doctrine/mongodb-odm-bundle dev-master 9748d11
doctrine/orm v2.4.7
gedmo/doctrine-extensions v2.3.9
stof/doctrine-extensions-bundle v1.1.0


Attachments: File migrate-example.php    

 Description   

i´m new to doctrine, but it seems to me that there is a problem creating statements in migrations.
Please see the //comments in the attached file!



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

Steve Müller I think I saw this issue already in the DBAL tracker somewhere, but I can't find it. Do you remember the issue ID?

Comment by Stefan Gnann [ 06/Feb/15 ]

The attached file was automatically generated after upgrading doctrine/dbal onto version 2.5.1 .

Now i have DOWNgraded doctrine/dbal to version 2.4.4 .
Suddenly the doctrine:migrations:diff says "No changes detected in your mapping information.".

Before downgrading i had two identical databases. One locally installed and one in a vagrant box with debian as os.
On every database i did a "doctrine:migrations:diff" to generate an actual schema update file. What i was wondering ist, that i got two different files with different ALTER xxxxx statements regarding to FOREIGN KEY and INDEXES.

Maybe this is a bug in doctrine/dbal 2.5.1?

Comment by Stefan Gnann [ 06/Feb/15 ]

actual installed bundles after downgrading:

doctrine/annotations v1.2.3
doctrine/cache v1.4.0
doctrine/collections v1.2
doctrine/common v2.4.2
doctrine/data-fixtures dev-master 80401e8
doctrine/dbal v2.4.4
doctrine/doctrine-bundle v1.3.0
doctrine/doctrine-cache-bundle v1.0.1
doctrine/doctrine-fixtures-bundle v2.2.0
doctrine/doctrine-migrations-bundle dev-master 81575a4
doctrine/inflector v1.0.1
doctrine/instantiator 1.0.4
doctrine/lexer v1.0.1
doctrine/migrations dev-master 1ac14fa
doctrine/mongodb 1.1.7
doctrine/mongodb-odm dev-master 1343375
doctrine/mongodb-odm-bundle dev-master 27e7690
doctrine/orm v2.4.7
gedmo/doctrine-extensions v2.3.11
stof/doctrine-extensions-bundle v1.1.0

Comment by Peter Rehm [ 18/Feb/15 ]

Steve Müller I did some research on that the last days and I am sure, there is still a major issue with the implementation.

The schema update creates the following sql commands:

$this->addSql('ALTER TABLE Article DROP FOREIGN KEY FK_12743CF7924C3225');
$this->addSql('ALTER TABLE Article DROP FOREIGN KEY FK_12743CF79395C3F3');
$this->addSql('ALTER TABLE Article DROP FOREIGN KEY FK_12743CF7F7C5BCDB');
$this->addSql('ALTER TABLE Article DROP FOREIGN KEY FK_93173F21A23B42D');
$this->addSql('ALTER TABLE Article DROP FOREIGN KEY FK_93173F21A5790FE9');
$this->addSql('ALTER TABLE Article ADD CONSTRAINT FK_12743CF7924C3225 FOREIGN KEY (createdUser_id) REFERENCES CoreUser (id)');

Looking at the previous SQL schema I found out that there is already e.g. the FK_12743CF7924C3225. This FK
will be dropped and newly added at the same time. It is actually not using the new FK name which doctrine would
like to see. However in the down sql it tried to drop the key which should be there.

In addition to that there is an issue with upper/lowercase Index names. This I got fixed by

return 'DROP INDEX ' . strtoupper($indexName) . ' ON ' . $table;

in MysqlPlatform:860 which is most likely not the right way. I am more concerned about the FK
issue, which I am unable to track down so far. Do you have any idea?

Comment by Peter Rehm [ 20/Mar/15 ]

@deeky666 Have you had a chance to look at this?





[DDC-3610] [GH-1328] [DDC-3609] Syntax error in class table inheritance join when WITH is used in DQL query Created: 10/Mar/15  Updated: 16/Mar/15

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

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


 Description   

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

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

Message:

I've added a test case to reproduce this issue. It's a bit contrived, but hopefully gives you enough to go on.



 Comments   
Comment by Doctrine Bot [ 16/Mar/15 ]

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





[DDC-3609] Syntax error in class table inheritance join when WITH is used in DQL query Created: 10/Mar/15  Updated: 16/Mar/15

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

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


 Description   

When using WITH on entities that use class table inheritance I'm seeing a syntax error in the generated SQL. Two "ON" statements show up:

INNER JOIN DDCNEWOrder d4_ ON d3_.id = d4_.id ON (d4_.id = d0_.id)

PR: https://github.com/doctrine/doctrine2/pull/1328



 Comments   
Comment by Doctrine Bot [ 16/Mar/15 ]

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





[DDC-2988] Notice: Undefined index: joinColumns in BasicEntityPersister.php Created: 19/Feb/14  Updated: 16/Mar/15

Status: Awaiting Feedback
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: 2.3.5, 2.4.2, 2.4.7
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Dennis Væversted Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 3
Labels: None

Attachments: Text File undefined-joinColumn.patch    
Issue Links:
Duplicate
duplicates DDC-2808 Notice: Undefined index: joinColumns ... Resolved
Reference
is referenced by DDC-3578 [GH-1307] Test for DDC-2988 Open

 Description   

When trying to use findBy on a ManyToMany field i receive the error:

Notice: Undefined index: joinColumns in lib/Doctrine/ORM/Persisters/BasicEntityPersister.php

It seems to be caused internally by the code expecting 'joinColumns' to be directly on the association, however it is found under 'joinTable'.
I have attached a patch that atleast fixes my case, hopefully it can be used to pin-point what the error is.



 Comments   
Comment by Dennis Væversted [ 19/Feb/14 ]

Might be related to this one: http://www.doctrine-project.org/jira/browse/DDC-2808

Comment by Litz Ouille [ 28/May/14 ]

Doctrine ORM 2.4.2 Here.

Here are my annotations
https://gist.github.com/LitzOuille/3cf2e73e169c032147ea

The thing I'm trying to do is
$questionRepository->findBy(array('contacts' => $ids)); // $ids = array(1,2,3, ...)

Comment by Marco Pivetta [ 30/May/14 ]

Calin Pristavu did you validate your mappings?

Comment by Calin Pristavu [ 30/May/14 ]

I failed, sorry.
The error came from the many-to-many condition in the entity.
Sorry for generating confusion, comment deleted !

The many-to-one works just fine !

Comment by Litz Ouille [ 03/Jun/14 ]

A little feedback? Is this a bug? Can it be fixed?
Thanks

Comment by Marco Pivetta [ 03/Jun/14 ]

Litz Ouille that particular repository call cannot work. How are we supposed to find an entity from a list of associated IDs? It would have to be the exact match...

Assuming that API would work as I envision it, it looks like a missing feature.

Dennis Væversted in order to accept a patch, we first need a failing test case demonstrating the failing scenario.

Comment by Litz Ouille [ 03/Jun/14 ]

EDIT: Ok my bad.

I am using findBy(array('id', $arrayIds)) and it is working. I thought I was using on a ManyToOne relationship, but no.

EDIT2: @ocramius In fact I would like to find all questions for which the contacts' list contains at least one id. Something like
SELECT q.*
FROM Question q, QuestionContact qc //qc = jointable
WHERE q.id = qc.question_id
AND qc.contact_id IN ($ids)

EDIT3: Actually when I try to findBy('ManyToMany', $id), it does not work either. I think I will have to use a repository for every query using a ManyToMany relationship.

EDIT4: Ok, so, as said in the original post, findBy does not work with many-to-many.
Notice: Undefined index: joinColumns (BasicEntityPersister.php line 1666)
Dump($this->class->associationMappings[$field]): https://gist.github.com/LitzOuille/51929fdc3eda5576ed31

Comment by Xander ten Boden [ 13/Jun/14 ]

I've got the same issue, also running doctrine 2.4.2:

multiple users can have multiple departments:

/**
 * @ORM\ManyToMany(targetEntity="CartelAuthDepartment", inversedBy="users")
 * @ORM\JoinTable(name="cartel_auth_user_has_cartel_auth_department",
 *		joinColumns={@ORM\JoinColumn(name="cartel_auth_user_id", referencedColumnName="id")},
 *		inverseJoinColumns={@ORM\JoinColumn(name="cartel_auth_department_id", referencedColumnName="id")}
 * )
 */
private $departments;

/**
 * @ORM\ManyToMany(targetEntity="\Cartel\AuthBundle\Entity\CartelAuth\CartelAuthUser", mappedBy="departments")
 */
private $users;

Then I want to find all the users that are within the departments that the current user has:

$aAuthUsers = $oEm->getRepository('CartelAuthBundle:CartelAuth\CartelAuthUser')->findByDepartments($aAuthDepartments);

This results in this error:

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

Comment by Alexander [ 29/Jan/15 ]

I have same problem with doctrine 2.4.7:

Acme\ProjectBundle\Entity\Employee:
  manyToMany:
    projectbag:
      targetEntity: ProjectBag
      mappedBy: bagemployee
Acme\ProjectBundle\Entity\ProjectBag:
  manyToMany:
    bagemployee:
          targetEntity: Employee
          inversedBy: projectbag
          joinTable:
            name: ProjectBag_Employee
            joinColumns:
              ProjectBag_id:
                referencedColumnName: id
            inverseJoinColumns:
              Employee_id:
                referencedColumnName: id

$em->getRepository('AcmeProjectBundle:ProjectBag')->findBy(array('bagemployee'=>$em->getRepository('AcmeProjectBundle:Employee')->find(828)));

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

Comment by George Brooks [ 06/Feb/15 ]

What is meant by "Awaiting feedback"?

After encountering the same error as described above I've created a new Symfony project with the sole purpose of reproducing the error. If this would be of use in resolving the issue please let me know. I can make the code available in whatever form would be the most useful.

Comment by Marco Pivetta [ 06/Feb/15 ]

in order to accept a patch, we first need a failing test case demonstrating the failing scenario.

We don't need a symfony project or an example app: we have our own test suite that can be found at https://github.com/doctrine/doctrine2/tree/master/tests

Comment by Carl Boisvert [ 13/Feb/15 ]

I have the same issue. Want to filter on a relationship on the owning side (Because I got an error on the non owning side saying I needed to be on the owning side) and I get the exact same error.

Comment by Ilya Antipenko [ 19/Feb/15 ]

As workaround we can collect IDs and pass it to queryBuilder, like:

    public function findAllSwitcherTypeByComponents($components)
    {
        $ids = [];
        /** @var Component $component */
        foreach ($components as $component) {
            $ids[] = $component->getId();
        }

        $query = $this->createQueryBuilder('component_switcher_type');
        $query
            ->join( 'component_switcher_type.components', 'components', 'WITH', $query->expr()->in('components.id', $ids));

        return $query->getQuery()->getResult();
}
Comment by Marco Pivetta [ 19/Feb/15 ]

Don't code workarounds: provide a test case, so that a patch can be created

Comment by Ilya Antipenko [ 19/Feb/15 ]

I'll this ASAP.

Comment by Ilya Antipenko [ 20/Feb/15 ]

Here is the test: https://github.com/doctrine/doctrine2/pull/1307
Here is the test log on travis-ci: https://travis-ci.org/aivus/doctrine2/builds/51516067

Comment by Doctrine Bot [ 16/Mar/15 ]

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





[DDC-3578] [GH-1307] Test for DDC-2988 Created: 20/Feb/15  Updated: 16/Mar/15

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

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

Issue Links:
Reference
relates to DDC-2988 Notice: Undefined index: joinColumns ... Awaiting Feedback

 Description   

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

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

Message:

This test can be merged only after fix issue DDC-2988

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



 Comments   
Comment by Doctrine Bot [ 16/Mar/15 ]

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





[DDC-3604] [GH-1323] - added isset validation for "inversedBy" Created: 08/Mar/15  Updated: 16/Mar/15

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

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


 Description   

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

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

Message:



 Comments   
Comment by Doctrine Bot [ 16/Mar/15 ]

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

Comment by Doctrine Bot [ 16/Mar/15 ]

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





[DDC-3592] [GH-1318] Respect the "unique" property of the join column on the owning side of a... Created: 27/Feb/15  Updated: 16/Mar/15

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

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

Issue Links:
Reference
relates to DDC-1666 orphanRemoval does not work with oneT... Resolved

 Description   

This issue is created automatically through a Github pull request on behalf of ed-at-work:

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

Message:

... One to One association. Coupled with Orphan Removal on the mapped side, this should provide better compatibility for replacing the row without getting duplicate key errors.



 Comments   
Comment by Doctrine Bot [ 16/Mar/15 ]

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

Comment by Doctrine Bot [ 16/Mar/15 ]

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





[DDC-3580] [GH-1308] [DDC-3579] Allow override of inversedBy Created: 20/Feb/15  Updated: 16/Mar/15

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

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


 Description   

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

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

Message:



 Comments   
Comment by Doctrine Bot [ 16/Mar/15 ]

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

Comment by Doctrine Bot [ 16/Mar/15 ]

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





[DDC-3584] [GH-1310] Allow symfony 3.0 components Created: 22/Feb/15  Updated: 16/Mar/15

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

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


 Description   

This issue is created automatically through a Github pull request on behalf of nicolas-grekas:

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

Message:

Tests should tell if any deprecated interfaces of Symfony are used. If not, then the bundle is defacto compatible with 3.0



 Comments   
Comment by Doctrine Bot [ 16/Mar/15 ]

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





[DDC-3539] [GH-1284] #1189 DDC-3406 derived identity in proxy must be a proxy Created: 24/Jan/15  Updated: 16/Mar/15

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

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

Issue Links:
Dependency
is required for DDC-3406 Proxy returns string instead of object Open

 Description   

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

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

Message:

This is a horrible hack for #1189.

Not happy with it, this seems like it fixes just the symptom.



 Comments   
Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 25/Jan/15 ]

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

Comment by Doctrine Bot [ 25/Jan/15 ]

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

Comment by Doctrine Bot [ 16/Mar/15 ]

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





[DDC-3618] Refactor PersistentCollection Created: 16/Mar/15  Updated: 16/Mar/15

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

Type: Improvement Priority: Major
Reporter: Varga Bence Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: collection, orm


 Description   

PersistentCollection - a final class - contains all the metadata, used to speed up updates (through $snapshot). This information should be removed from the collection object and stored elsewhere, loosely coupled.

Doctrine2 uses the data mapper pattern (instead of Doctrine1's active record approach). This tells me that the designers see the importance of freedom which comes with loose coupling. Entities don't have to extend fixed base classes, why do collections?

Use case: I would like to use a wrapper around Collection (my current environment requires collections to have a certain functionality). This is possible in theory, but as I do the first step I'm losing all the advantages coming with PersistentColelction. Since it is a final class and logically an interface by itself (see the sniffing in ObjectHydrator#initRelatedCollection) it is impossible to create a wrapper which exposes the same functionality.

A short-term solution would be to extract an interface from PersistentColelction. A long-term one would be to manage the persisted state (currently PersistentCollection#snapshot) elsewhere (accessed through the EntityManager maybe).






[DDC-3413] Types are always ignored when performing a one to many statement Created: 26/Nov/14  Updated: 12/Mar/15

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

Type: Bug Priority: Major
Reporter: Edouard COLE Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: persister


 Description   

BasicEntityPersister#getOneToManyStatement() is building an array named $criteria. This array is built this way:

$criteria[$tableAlias . "." . $targetKeyColumn] = ...;

This means this array is indexed by keys looking like that:

t0.fieldName

But the function BasicEntityPersister#expandParameters() is used in this function, and this function is NOT able to handle SQL field name as keys, but PHP attributes, because it uses BasicEntityPersister#getType() which is doing this:

case (isset($this->class->fieldMappings[$field])):
case (isset($this->class->associationMappings[$field])):

I think the $criteria array should be used to call BasicEntityPersister#getSelectSQL(), but another array should be passed to expandParameters. Here is a potential fix:

$cleanCriteria[$owningAssoc['fieldName']] = $criteria[$tableAlias . "." . $targetKeyColumn] = ...;

And $cleanCriteria should be passed to expandParameters.



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

Edouard COLE I suggest you to open a pull request with a failing test case, otherwise this issue is hard to follow/understand.

Comment by Edouard COLE [ 12/Mar/15 ]

I think this issue is fixed since https://github.com/doctrine/doctrine2/commit/ce446a6f033ca46fc65911e6f40299336ddace74





[DDC-3612] Make SQLFilter#em protected Created: 11/Mar/15  Updated: 11/Mar/15

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

Type: Improvement Priority: Minor
Reporter: Evan Owens Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

SQLFilter#em is private, which can be troublesome when extending SQLFilter. I notice, for example, that the Gedmo SoftDeleteableFilter goes to the trouble of using reflection to get access to SoftDeleteableFilter#em.






[DDC-3605] [GH-1324] load all many to many join columns Created: 08/Mar/15  Updated: 10/Mar/15

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

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


 Description   

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

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

Message:

the ```$joinColumnElement``` variable is created inside the foreach loop, and used only after it finishes, causing only the last join column to be loaded.



 Comments   
Comment by Doctrine Bot [ 10/Mar/15 ]

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

Comment by Doctrine Bot [ 10/Mar/15 ]

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





[DDC-3603] Readonly columns Created: 06/Mar/15  Updated: 06/Mar/15

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

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


 Description   

Sometimes I have a column that is calculated (or have a default value) at the database side. When inserting a new record doctrine issues NULL into such a column that causes problems on some DBMS. I would like to annotate such columns as readonly so that doctrine would skip them in INSERT and UPDATE clauses but still fetch them in SELECT clauses.






[DDC-3602] allow regex in filter option for convert-mapping cli Created: 05/Mar/15  Updated: 05/Mar/15

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

Type: New Feature Priority: Major
Reporter: Jochem Blok Assignee: Steve Müller
Resolution: Unresolved Votes: 0
Labels: cli, convert-mapping, filter


 Description   

It is possible to use the filter option to filter which table is converted. It uses as strpos function of php. Please enable the power of regular expressions.






[DDC-3600] Implement include columns annotation for indexes Created: 05/Mar/15  Updated: 05/Mar/15

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

Type: Bug Priority: Major
Reporter: Jochem Blok Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: annotation, index, mssql, sqlserver
Environment:

Sql Server



 Description   

Sql server has an option to include columns in an index. There is no (optional) annotation for this functionality. http://doctrine-orm.readthedocs.org/en/latest/reference/annotations-reference.html#annref-index



 Comments   
Comment by Marco Pivetta [ 05/Mar/15 ]

Why would you need this sort of feature, when an index already defines the included columns?

Comment by Jochem Blok [ 05/Mar/15 ]

the advantages are described on the MSDN website:

By including nonkey columns, you can create nonclustered indexes that cover more queries. This is because the nonkey columns have the following benefits:
They can be data types not allowed as index key columns.
They are not considered by the Database Engine when calculating the number of index key columns or index key size.





[DDC-3601] @index where annotation not filled with convert-mapping cli Created: 05/Mar/15  Updated: 05/Mar/15

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

Type: Bug Priority: Major
Reporter: Jochem Blok Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: annotation, cli, convert-mapping, index, mssql, sqlserver
Environment:

Sql Server



 Description   

When you use the CLI tool "orm:convert-mapping --from-database xml" the generated XML file does not contain the optional WHERE for the indexes. It look like this is not implemented in de Doctrine\ORM\Tools\Export\Driver\XmlExporter






[DDC-3423] Column Ordering when creating tables using doctrine:schema:update Created: 01/Dec/14  Updated: 05/Mar/15

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

Type: Improvement Priority: Minor
Reporter: Raja Venkataraman Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 3
Labels: None


 Description   

When you have a Base class (annotated with @MappedSuperClass) having some columns, say, createdById, createdDateTime and child entities deriving from the BaseClass, the ordering of the SQL when running doctrine:schema:update looks like

createdById
createdDateTime
id
field1
field2

i.e. the columns of the Base class come up first and then that of the children. It looks odd when you write a SQL to insert into these tables because the default ordering is not what you expect (Which would be derived class columns first and then base class).

I looked into ClassMetadataFactory that adds the fields to the classmetadata and figured if we could move the following
$this->addInheritedFields($class, $parent);
$this->addInheritedRelations($class, $parent);

to after the point where the local fields are added to the classmetadata, this problem is solved.

It might be even better if we have an annotation to specify the Ordering of columns but nevertheless this will help in cases where the base class columns appear after the derived class columns.

Note: Did look into columnDefinition annotation to specify a "AFTER <column>", but that cannot be used during CREATE TABLE, only for ALTER TABLE and that too, its mysql specific.



 Comments   
Comment by Michael Topor-Grabowski [ 05/Mar/15 ]

This would be a great feature. I am using inheritance in the entity classes and have the same problem.
Even if this is not a common taks for ORM, but i simplifies your life





[DDC-3598] Paginator incorrect ordering Created: 03/Mar/15  Updated: 03/Mar/15

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

Type: Bug Priority: Major
Reporter: Kris Assignee: Steve Müller
Resolution: Unresolved Votes: 0
Labels: paginator


 Description   

When ordering by multiple fields, with the order by fields not contained in the original select statement the paginator outputs in an incorrect order.
I found the issue is in the LimitSubqueryOutputWalker in the preserveSqlOrdering function. This is the query it generates

SELECT DISTINCT id1, date_added3 FROM (SELECT t0_.description AS description0, t0_.id AS id1, t0_.date AS date2, t0_.date_added AS date_added3 FROM Ticket t0_ INNER JOIN user u1_ ON t0_.assigned_user_id = u1_.id INNER JOIN user u2_ ON t0_.created_user_id = u2_.id WHERE t0_.project_id = ? ORDER BY u2_.first_name DESC, t0_.date_added DESC) dctrn_result ORDER BY date_added3 DESC

So it appears that it ignores any order by field that is not included in the inner select statement.






[DDC-3596] Do not allow entity column name "decimal" or escape somehow Created: 02/Mar/15  Updated: 02/Mar/15

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

Type: Bug Priority: Major
Reporter: Aurimas Niekis Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Problem is that after creation and schema update of entity with property "decimal" it makes problem to insert and alter that column.

On schema update it uses this SQL to create table:

CREATE TABLE Unit (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, unit VARCHAR(255) NOT NULL, `decimal` SMALLINT NOT NULL, decimal_point VARCHAR(1) NOT NULL, thousands_separator VARCHAR(1) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;

When trying to persist entity I get exception

  [Doctrine\DBAL\DBALException]
  An exception occurred while executing 'INSERT INTO Unit (name, unit, decimal, decimal_point, thousands_separator) VALUES (?, ?, ?, ?, ?)' with params ["Cubic meters", "m\u00b3", "2", ".", ","]:
  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'deci
  mal, decimal_point, thousands_separator) VALUES ('Cubic meters', 'm³', '2',' at line 1

Or alter table to rename column

  [Doctrine\DBAL\DBALException]
  An exception occurred while executing 'ALTER TABLE Unit CHANGE decimal decimal_numbers SMALLINT NOT NULL':
  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'deci
  mal decimal_numbers SMALLINT NOT NULL' at line 1





[DDC-3593] INDEX BY doesnt't work for NEW ArticleDTO Created: 01/Mar/15  Updated: 01/Mar/15

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

Type: Bug Priority: Major
Reporter: Ondřej Vodáček Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

With this query the resulting array is not indexed by id, but from zero

Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
$query = $em->createQuery('SELECT NEW ArticleDTO(a.id, a.title) FROM Article a INDEX BY a.id');
$articles = $query->getResult();





[DDC-3582] Nested embeddables are instantiated with the wrong class Created: 22/Feb/15  Updated: 27/Feb/15

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

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


 Description   

Consider the example where an entity contains an embeddable, that itself contains 2 different embeddables. So Entity -> Embeddable 1 -> (Embeddable 2, Embeddable 3). In this case, Embeddable1 will be instantiated as an Embeddable2 for some reason.

Please see https://github.com/jankramer/doctrine2/commit/5e6b02a0fa9a1216b4e4d075061619288af74e7a for a test that demonstrates this and currently fails.

I looked at the code in the ReflectionEmbeddedProperty, and noticed that 'embeddedClass' was recently changed from 'class'. If I change it back, this test passes, but then the ReflectionEmbeddedPropertyTest fails on the scenario for abstract classes. @ocramius, I saw you were the author on that change, could you please take a look? Thanks!



 Comments   
Comment by Jan Kramer [ 22/Feb/15 ]

Closing this as I can't seem to reproduce this issue anymore.

Comment by Jan Kramer [ 24/Feb/15 ]

Now able to reproduce this issue, updated the description.

Comment by Marco Pivetta [ 24/Feb/15 ]

Jan Kramer please send a PR with that diff

Comment by Jan Kramer [ 24/Feb/15 ]

@ocramius See https://github.com/doctrine/doctrine2/pull/1311

Comment by Doctrine Bot [ 27/Feb/15 ]

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

Comment by Doctrine Bot [ 27/Feb/15 ]

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





[DDC-3583] [GH-1309] [DDC-3582] Fix hydration of nested embeddables Created: 22/Feb/15  Updated: 27/Feb/15

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

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


 Description   

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

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

Message:

The wrong class is chosen when hydrating embeddables that are part of a nested structure. See `DDC3582Test` for a demonstration. The fix is to use `class` instead of `embeddedClass` to instantiate the embeddable in ReflectionEmbeddedProperty.

The test I removed from ReflectionEmbeddedPropertyTest was failing because you cannot instantiate an abstract class (and rightfully so). However, as this would not be possible in practice anyway (you always end up extending the abstract class), I think this test can be removed safely.



 Comments   
Comment by Doctrine Bot [ 22/Feb/15 ]

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

Comment by Doctrine Bot [ 27/Feb/15 ]

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

Comment by Doctrine Bot [ 27/Feb/15 ]

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





[DDC-128] Consider adding EntityManager#link/unlink methods for direct association manipulation Created: 07/Nov/09  Updated: 24/Feb/15

Status: Awaiting Feedback
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA2
Fix Version/s: 2.x
Security Level: All

Type: New Feature Priority: Major
Reporter: Roman S. Borschel Assignee: Roman S. Borschel
Resolution: Unresolved Votes: 1
Labels: None

Issue Links:
Reference
is referenced by DDC-546 New fetch mode EXTRA_LAZY for collect... Resolved

 Description   

A problem when working with collection-valued associations is that almost all operations except add($obj) require the collection to become initialized in order for the operation to be performed properly. While this is all correct and beautiful OO-wise it may be problematic at times with regards to performance. Hence we might want to consider to provide some convenient methods along the lines of link/unlink (name suggestions?) which allow more direct, less OO collection manipulation. Such methods obviously would bypass the normal object lifecycle and the changes done through these methods will not be reflected in the in-memory objects and collections, unless the user keeps them in-synch himself.



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

Questions

  • I suppose link and unlinked entities would then handled by UnitOfwork commit also?
  • Since the collection is not initialized, one does not know upfront if the action will be successful, what happens if:
    • an entity is linked with a collection, although they are already connected.
    • an entity is unlinked from a collection it is not in.

Regarding the naming, i like link/unlink.

Comment by Roman S. Borschel [ 17/Dec/09 ]

What do you mean by "handled by UnitOfWork commit" ? Whether the SQL is "scheduled" or executed immediately? Interesting question.
Scheduling would probably be better but also more difficult.

As far as usage is concerned, I currently imagine it as follows:

// EntityManager#link($sourceObj, $field, $targetObj)
$user = $em->getReference($userId); // $userId probably from request parameters
$address = $em->getReference($addressId); // $addressId probably from request parameters
$em->link($user, 'addresses', $address);

"What happens if: an entity is linked with a collection, although they are already connected."

Probably an SQL error which results in an exception from the driver. Depends on the database constraints though.

"What happens if: an entity is unlinked from a collection it is not in"

Probably nothing, at least not from the SQL side. An exception could be thrown from Doctrine itself if the update affected 0 rows.

Thanks for these initial questions. Thats definitely food for thought. Keep it coming.

Comment by Roman S. Borschel [ 26/Aug/10 ]

Pushed back.





[DDC-2556] Proxy getId() different code generated when using Trait Created: 16/Jul/13  Updated: 23/Feb/15

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

Type: Bug Priority: Minor
Reporter: Eduardo Oliveira Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: None


 Description   
class Timezone {
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="smallint", nullable=false, options={"unsigned": true})
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

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

If I replace that code with a Trait with equal code and use it on the entity the proxy will be generated different.

Without trait:

    /**
     * {@inheritDoc}
     */
    public function getId()
    {
       	if ($this->__isInitialized__ === false) {
            return (int)  parent::getId();
        }


       	$this->__initializer__ && $this->__initializer__->__invoke($this, 'getId', array());

       	return parent::getId();
    }

With trait:

    /**
     * {@inheritDoc}
     */
    public function getId()
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getId', array());

        return parent::getId();
    }

And in this code:

$timezone = $this->timezoneRepository->findReadOnly(
    $campaign->getTimezone()->getId()
);

I get:
Doctrine\ORM\ORMException: The identifier id is missing for a query of EB\Core\KernelBundle\Entity\Common\Timezone

$campaign->getTimezone()->getId()
Is returning null.

About the findReadOnly is just a wrapper that will fetch from cache if not there fetch from DB, anyway if I change it to find() exact same problem

My versions of doctrine:

$ php composer.phar show -i | grep doctrine
doctrine/annotations                   v1.1.2             Docblock Annotations Parser
doctrine/cache                         v1.0               Caching library offering an object-oriented API for many cache backends
doctrine/collections                   v1.1               Collections Abstraction library
doctrine/common                        2.4.0-RC4          Common Library for Doctrine projects
doctrine/data-fixtures                 dev-master 6924952 Data Fixtures for all Doctrine Object Managers
doctrine/dbal                          2.4.0-RC2          Database Abstraction Layer
doctrine/doctrine-bundle               v1.2.0             Symfony DoctrineBundle
doctrine/doctrine-fixtures-bundle      dev-master 512fc0f Symfony DoctrineFixturesBundle
doctrine/doctrine-migrations-bundle    dev-master 5fc1167 Symfony DoctrineMigrationsBundle
doctrine/inflector                     v1.0               Common String Manipulations with regard to casing and singular/plural rules.
doctrine/lexer                         v1.0               Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers.
doctrine/migrations                    dev-master ced3b41 Database Schema migrations using Doctrine DBAL
doctrine/orm                           2.4.0-RC2          Object-Relational-Mapper for PHP
gedmo/doctrine-extensions              v2.3.6             Doctrine2 behavioral extensions
stof/doctrine-extensions-bundle        dev-master 6577f23 Integration of the gedmo/doctrine-extensions with Symfony2


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

Is the problem here the repository or just the trait method?

Can you please clean up the issue to insulate only the affected part? What is `getId` returning on that kind of object?

Comment by Eduardo Oliveira [ 16/Jul/13 ]

Marco I will try to do better, I will try to do make a test case that proves this.

But i can leave here already more info:

  • There is an entity Campaign that have a Timezone (ManyToOne in Campaign side);
  • This entity Campaign is fetch (with lazy in all associations) and serialized and put in cache;
  • This entity Campaign don't have timezone itself, but $campaign->getTimezone()->getId() hit the return (int) parent::getId(); on proxy not making any query to get the timezone, in the case with trait the proxy code is different and it returns null
Comment by Marco Pivetta [ 16/Jul/13 ]

Eduardo Oliveira is the proxy in a detached state when you do this? What happens if (with an existing identifier) you do following?

var_dump($entityManager->getReference('Timezone', 123)->getId());
Comment by Eduardo Oliveira [ 16/Jul/13 ]
var_dump ( $this->timezoneRepository->getEM()->getReference('EBCoreKernelBundle:Common\Timezone', 1)->getId() ); // 1

Marco yes is on detached mode, and I know that, I'm relying on the proxy to get the ID, because I don't want any queries being "issued", so I'm doing like

$campaign = $campaignRepository->findReadOnly(10); // hit cache
$timezoneRepository->findReadOnly($campaign->getTimezone()->getId() /* rely on proxy */); // hit memcache

This just work in the last versions of Doctrine that have lazy getId(), but it looks that for traits something wrong happens on the generation of Proxy.

If on Entity timezone I use the trait but override the getId() everything works perfect again.

Comment by Marco Pivetta [ 16/Jul/13 ]

Eduardo Oliveira does this also happen with 2.3.x? (asking because the proxy generation logic was rewritten for 2.4)

Comment by Eduardo Oliveira [ 16/Jul/13 ]

2.3 the proxy is quite different but the essence of the problem remains:

Proxy with trait (doesn't work, because as far as I know will try to make a query in detach mode):

    public function getId()
    {
        $this->__load();
        return parent::getId();
    }

Proxy without trait (works well):

    public function getId()
    {
        if ($this->__isInitialized__ === false) {
            return (int) $this->_identifier["id"];
        }
        $this->__load();
        return parent::getId();
    }
Comment by Marco Pivetta [ 16/Jul/13 ]

Ok, so at least I now know it's not an issue with the upgrade, but it was also borked before. Thanks for following along till here: I'll work on a patch as soon as I have time.

Comment by Thomas Ploch [ 23/Feb/15 ]

@ocramius

This just got a little bit hotter for us. We moved all our ID related code into a trait that is shared by most our entities. After deploying that we saw a dramatic rise in small id based queries to the database, which is related to this bug here.

We had to revert the changes for now, but I'd be happy to work on a fix if there still is a need.

Regards
Thomas

Comment by Thomas Ploch [ 23/Feb/15 ]

See http://www.doctrine-project.org/jira/browse/DCOM-276





[DDC-3581] DatabaseDriver does not assert nullable on ToOne associationMappings Created: 21/Feb/15  Updated: 21/Feb/15

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

Type: Improvement Priority: Minor
Reporter: Ryan Korczykowski Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: None


 Description   

I am using the DatabaseDriver/AnnotationExporter to tweak class generation and found that JoinColumn annotations did not contain nullable=false even when the local FK column was not null. This is counter-intuitive since nullable on Column annotations is properly handled.

Here is a simple fix that checks the column of the local column in DatabaseDriver::buildToOneAssociationMappings:

for ($i = 0; $i < count($fkColumns); $i++) {
    $associationMapping['joinColumns'][] = array(
        'name'                 => $fkColumns[$i],
        'referencedColumnName' => $fkForeignColumns[$i],
        //fix here
        'nullable' => !$foreignKey->getLocalTable()->getColumn($fkColumns[$i])->getNotNull()
    );
}

Given that the database defines null / not null on FK columns, the JoinColumn nullable attribute should not be left undefined.






[DDC-3577] Inherited associations are ignored Created: 20/Feb/15  Updated: 20/Feb/15

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

Type: Bug Priority: Major
Reporter: Denis Vasilev Assignee: Steve Müller
Resolution: Unresolved Votes: 0
Labels: schematool


 Description   

Could not create schema via SchemaTool for entity, which has inherited accosiation mapping (this mapping is ignored).

ShemaTool.php
private function gatherRelationsSql($class, $table, $schema, &$addedFks, &$blacklistedFks)
{
    foreach ($class->associationMappings as $mapping) {
        if (isset($mapping['inherited'])) {
            continue;
        }
...

I have three entity types:

  • BaseType — mapping mapped-superclass, has association many-to-one, join-column pid
  • SecondType extends BaseType — mapping entity
  • ThirdType extends SecondType — mapping entity

Table for ThirdType not has pid column after created scheme via SchemeTool. Inheritance mapping not using.



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

This should actually be working: you probably need to provide a test case otherwise

Comment by Denis Vasilev [ 20/Feb/15 ]

https://github.com/yethee/doctrine2/commit/d55a8bc71381db1c599da682c4baca0ce39d0d62
Test case for this issue.

$ phpunit --group=DDC-3577
PHPUnit 4.7-g7c1de6a by Sebastian Bergmann and contributors.

Configuration read from D:\Projects\doctrine2\phpunit.xml.dist

F

Time: 1.97 seconds, Memory: 81.75Mb

There was 1 failure:

1) Doctrine\Tests\ORM\Tools\SchemaToolTest::testInheritedAssociationShouldBeSupported
Table "ddc3577_interviews" should has column "user_id".
Failed asserting that false is true.




[DDC-3579] Allow override of inversedBy Created: 20/Feb/15  Updated: 20/Feb/15

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

Type: New Feature Priority: Minor
Reporter: z38 Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: inheritance


 Description   

If an entity inherits a many-to-many relationship it is sometimes desirable to be allowed to override inversedBy. This way bi-directional relationships can exist without code duplication. For examples, check out this and this Stackoverflow question.

The proposed pull-request implements this feature. I'm open to any comments and suggestions. Please just let me know if this feature is opposed to any concepts/practices, I'm not sure whether the feature is needed by anyone else.






[DDC-3575] Paginator's CountOutputWalker keeps the ORDER BY in the subquery for all non-MSSQL platforms Created: 20/Feb/15  Updated: 20/Feb/15

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

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

Issue Links:
Reference
relates to DDC-3519 [GH-1267] Failing test for an ORDER B... Resolved
relates to DDC-3538 [GH-1283] #1267 - order by broken in ... Resolved

 Description   

The Paginator's CountOutputWalker leaves the ORDER BY clause in the subquery that's executed to get the total count.

The original (and current) version of that code included the following comment:

Note that the ORDER BY clause is not removed. Many SQL implementations (e.g. MySQL) are able to cache subqueries. By keeping the ORDER BY clause intact, the limitSubQuery that will most likely be executed next can be read from the native SQL cache.

My understanding is that MySQL does not, in fact, cache subqueries in the query cache, so cached results are not available between executions of different queries. The current MySQL manual still states that "Queries that are a subquery of an outer query" are not cached.

This pull request was merged in 2013 to address errors with mssql and paginating ordered queries. Midway through the discussion on that issue, it was determined that it would be better to just remove the ORDER BY clause for all platforms, not just MS SQL. However, that decision was reversed when it came time to merge the PR.

Does the comment on that method accurately describe the rationale for retaining the ORDER BY clause for the count query? If so, am I simply wrong about how MySQL operates, or does the comment refer to some other platform that benefits from this pattern?



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

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

This change was reverted because MSSQL is pretty much a niche, and fixing bugs for it is really making things complicated for all the other storages.

Comment by John Flatness [ 20/Feb/15 ]

Thanks for the reply, Marco.

I think this is getting conflated with the other Paginator-related ORDER BY changes and reversions that have happened breaking and fixing the actual sorting behavior. The pull you linked looks like its relating to the LimitSubqueryOutputWalker, not the CountOutputWalker.

The thing I'm talking about is still there, and does specifically address only a MSSQL bug: https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Tools/Pagination/CountOutputWalker.php#L82

The particular part of the discussion on PR #572 I was referring to above is here: https://github.com/doctrine/doctrine2/pull/572#discussion_r3154962

My concern is that the rationale for keeping the ORDER BY intact for all the other platforms (only when running the count query, not the "real" one) is a performance-related one, and that it's a flawed rationale. (Or, at least, that the comment about it is.)





[DDC-3573] DateTime objects casted to string when used in aggregate functions in query results Created: 18/Feb/15  Updated: 18/Feb/15

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

Type: Bug Priority: Major
Reporter: Ameer Antar Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: dbal, mysql, orm, querybuilder
Environment:

MySQL, possibly others



 Description   

Similar to DDC-657: http://www.doctrine-project.org/jira/browse/DDC-657

DateTime objects are converted to strings when selecting them through an aggregate function.

Example:

Update.php Column definition
    /**
     * @var \DateTime
     * @ORM\Column(name="entryDate", type="datetime")
     */
    private $entryDate;
Query Builder
		$qb = $this->getEntityManager()->createQueryBuilder();
		$qb->select('u.code, max(u.entryDate) as updateDate');
		$qb->from('Update', 'u');
		$qb->addGroupBy('u.code');

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

The result contains the date/times as strings not DateTime objects as expected. This affects the query builder. I assume it also affects DQL queries.






[DDC-3571] Alter ResultSetMapping on NEW DQL (typeMapping for newObjectMappings) Created: 17/Feb/15  Updated: 17/Feb/15

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

Type: Documentation Priority: Minor
Reporter: Ignace Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None


 Description   

In the documentation it says that with the NEW operator only scalars are passed but it is limited to only string? Or is it possible to hint it to return floats and integers aswell?

Currently I hacked this together:

private function getIncomeOutgoingPerMonthQuery($year, &$rsm)
    {
        $rsm = new ResultSetMapping();
        $rsm->addScalarResult('sclr0', 'amount_sum', 'integer');

        return $this->createQueryBuilder('t')
            ->select('NEW AppBundle\ValueObject\Money(SUM(t.amount), t.currency), SUBSTRING(t.date, 6, 2) AS HIDDEN month')
            ->where('SUBSTRING(t.date, 1, 4) = :year')
            ->groupBy('t.currency')
            ->addGroupBy('month')
            ->setParameter('year', (int)$year);
    }





[DDC-3460] SchemaTool create unnecessry work by trying to set foreign keys on MyISAM tables Created: 20/Dec/14  Updated: 16/Feb/15

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

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


 Description   

When I run SchemaTool::getSchemaFromMetadata, it always adds foreign keys constraints for all association fields (in SchemaTool::gatherRelationJoinColumns). Since I've set the table's engine option to 'MyISAM', this is quite pointless, since they won't get created anyways.

When I run SchemaManager::createSchema, it does not detect any foreign keys, so the SchemaDiff from Comparator will contain a large number of (pointless) ADD CONSTRAINT FK_xxx FOREIGN KEY commands.

For the moment, I work around this by removing them in a ToolEvents::postGenerateSchemaTable listener, but shouldn't SchemaTool be able to detect this situation itself?



 Comments   
Comment by flack [ 16/Feb/15 ]

This says "awaiting feedback" now. Is there any question that I can answer?

Comment by Marco Pivetta [ 16/Feb/15 ]

I think this is a "won't fix", as we don't consider MyISAM as supported.

The "awaiting feedback" flag was mainly because tests are missing.

Comment by Steve Müller [ 16/Feb/15 ]

I think we fixed that already in DBAL 2.5: https://github.com/doctrine/dbal/commit/e95afefab614ecb352791cf09fd5f831d7e5b3be





[DDC-3550] [GH-1293] EntityManager::__cosntruct() as public method Created: 28/Jan/15  Updated: 16/Feb/15

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

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


 Description   

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

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

Message:



 Comments   
Comment by Doctrine Bot [ 16/Feb/15 ]

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





[DDC-3259] Second level & UnitOfWork inconsistencies Created: 19/Aug/14  Updated: 16/Feb/15

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

Type: Improvement Priority: Major
Reporter: Asmir Mustafic Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: second-level-cache


 Description   

Hi!

I have a lot of entities with entity associations as keys and I'm trying to use second level cache.

Looking at the method: UnitOfWork::createEntity($className, array $data, &$hints = array())

  • $className: contains the class name
  • $data: contains the raw data (the row coming from the database)

Enabling the second level cache, DefaultQueryCache::get calls the createEntity method passing a $data that contains object entities and some raw data (https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Cache/DefaultQueryCache.php#L155).

I think that DefaultQueryCache should not introduce a variant of $data and should create a compatible version of $data.



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

Asmir Mustafic do you have any example of where this may be happening?

Comment by Asmir Mustafic [ 19/Aug/14 ]

https://github.com/doctrine/doctrine2/pull/1114

This is the same branch of https://github.com/doctrine/doctrine2/pull/1113, plus this commit (https://github.com/goetas/doctrine2/commit/bfbbb9123fd28f7fa053b76895eaa77e00095aa6) that simply involves the second level cache too.
Travis should fail soon.

Comment by Doctrine Bot [ 19/Aug/14 ]

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

Comment by Asmir Mustafic [ 19/Aug/14 ]

Here the failure https://travis-ci.org/doctrine/doctrine2/jobs/32972996#L402

Comment by Doctrine Bot [ 22/Oct/14 ]

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

Comment by Doctrine Bot [ 18/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 16/Feb/15 ]

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





[DDC-2879] Persisting collections with Composite Primary Keys composed of 2 Foreign Keys and one metadata field Created: 31/Dec/13  Updated: 16/Feb/15

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

Type: Bug Priority: Major
Reporter: Dylan Johnson Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: composite, identity, mapping, orm, postgresql
Environment:

Ubuntu 13.04 and PostgresSQL 9.1.0 on Vagrant Virtual Machine running an application with Symfony2 backend and JavaScript client



 Description   

SYNOPSIS

Bug prevents persisting a collection of entities in a join table with a Composite Primary
Key made up of 2 Foreign Keys and one metadata field. From these mapping instructions:
http://docs.doctrine-project.org/en/latest/tutorials/composite-primary-keys.html#use-case-3-join-table-with-metadata

ISSUE DETAILS

SUCCESS: When FOREIGN KEY 1 is the same across items in a collection to be persisted, and FOREIGN KEY 2 is greater than FOREIGN KEY 2 in any existing PRIMARY KEY, the entity and collection are persisted correctly

    • Example: GPA "add val below" exists and has assessment value
      {"grade_point_average_id":1,"assessment_id":1,"value":4}

      We will try to add a new assessment value where assessment_id > that of any existing assessment value for GPA "add val below"

    • Request Payload:
      {"name":"Add Val Below","courses":[],"assessmentValues":[{"assessment":1,"value":4},{"assessment":3,"value":2}]}
    • Debug Log:
      [2014-01-07 11:48:01] app.INFO: START GRADE_POINT_AVERAGE_REPOSITORY #SAVE [GPA #GET_NAME =ADD VAL BELOW] [] []
      [2014-01-07 11:48:01] app.INFO:   BEGIN OUTPUT FOR GRADE POINT AVERAGE Add Val Below - ASSESSMENT VALUE 1 [] []
      [2014-01-07 11:48:01] app.INFO:         ASSESSMENT_VALUE #GET_GRADE_POINT_AVERAGE #GET_ID: 1 [] []
      [2014-01-07 11:48:01] app.INFO:         GRADE_POINT_AVERAGE #GET_ID: 1 [] []
      [2014-01-07 11:48:01] app.INFO:         ASSESSMENT_VALUE #GET_ASSESSMENT #GET_ID: 1 [] []
      [2014-01-07 11:48:01] app.INFO:         ASSESSMENT_VALUE #GET_VALUE: 4 [] []
      [2014-01-07 11:48:01] app.INFO:         MANAGED? 1 [] []
      [2014-01-07 11:48:01] app.INFO:   END OUTPUT FOR GRADE POINT AVERAGE Add Val Below - ASSESSMENT VALUE 2 [] []
      [2014-01-07 11:48:01] app.INFO:   BEGIN OUTPUT FOR GRADE POINT AVERAGE Add Val Below - ASSESSMENT VALUE 2 [] []
      [2014-01-07 11:48:01] app.INFO:         ASSESSMENT_VALUE #GET_GRADE_POINT_AVERAGE #GET_ID: 1 [] []
      [2014-01-07 11:48:01] app.INFO:         GRADE_POINT_AVERAGE #GET_ID: 1 [] []
      [2014-01-07 11:48:01] app.INFO:         ASSESSMENT_VALUE #GET_ASSESSMENT #GET_ID: 3 [] []
      [2014-01-07 11:48:01] app.INFO:         ASSESSMENT_VALUE #GET_VALUE: 2 [] []
      [2014-01-07 11:48:01] app.INFO:         MANAGED?  [] []
      [2014-01-07 11:48:01] app.INFO:   END OUTPUT FOR GRADE POINT AVERAGE Add Val Below - ASSESSMENT VALUE 3 [] []
      [2014-01-07 11:48:01] app.INFO: END GRADE_POINT_AVERAGE_REPOSITORY #SAVE [GPA #GET_NAME =ADD VAL BELOW] [] []
      [2014-01-07 11:48:01] doctrine.DEBUG: "START TRANSACTION" [] []
      [2014-01-07 11:48:01] doctrine.DEBUG: INSERT INTO gpa_assessment_value (point_value, grade_point_average_id, assessment_id) VALUES (?, ?, ?) {"1":2,"2":"1","3":"3"} []
      [2014-01-07 11:48:01] doctrine.DEBUG: UPDATE gpa_assessment_value SET point_value = ? WHERE grade_point_average_id = ? AND assessment_id = ? [4,1,1] []
      [2014-01-07 11:48:01] doctrine.DEBUG: "COMMIT" [] []

FAILURE: When FOREIGN KEY 1 is the same across items in a collection, and FOREIGN KEY 2 is less than any existing FOREIGN KEY 2, the unit of work tries to INSERT existing entity and does not operate on new entity. The EntityManager thinks it contains() the new entity, but not the old one

    • Example: GPA "add val above" exists and has assessment value
      {"assessment":3,"value":2}

      We will try to add a new assessment value where assessment_id < that of any existing assessment value for GPA "add val above"

    • Request Payload:
      {"name":"Add Val Above","courses":[],"assessmentValues":[{"assessment":1,"value":4},{"assessment":3,"value":2}]}
    • Debug log:
      [2014-01-07 11:47:09] app.INFO: START GRADE_POINT_AVERAGE_REPOSITORY #SAVE [GPA #GET_NAME =ADD VAL ABOVE] [] []
      [2014-01-07 11:47:09] app.INFO:   BEGIN OUTPUT FOR GRADE POINT AVERAGE Add Val Above - ASSESSMENT VALUE 1 [] []
      [2014-01-07 11:47:09] app.INFO:         ASSESSMENT_VALUE #GET_GRADE_POINT_AVERAGE #GET_ID: 2 [] []
      [2014-01-07 11:47:09] app.INFO:         GRADE_POINT_AVERAGE #GET_ID: 2 [] []
      [2014-01-07 11:47:09] app.INFO:         ASSESSMENT_VALUE #GET_ASSESSMENT #GET_ID: 1 [] []
      [2014-01-07 11:47:09] app.INFO:         ASSESSMENT_VALUE #GET_VALUE: 4 [] []
      [2014-01-07 11:47:09] app.INFO:         MANAGED? 1 [] []
      [2014-01-07 11:47:09] app.INFO:   END OUTPUT FOR GRADE POINT AVERAGE Add Val Above - ASSESSMENT VALUE 2 [] []
      [2014-01-07 11:47:09] app.INFO:   BEGIN OUTPUT FOR GRADE POINT AVERAGE Add Val Above - ASSESSMENT VALUE 2 [] []
      [2014-01-07 11:47:09] app.INFO:         ASSESSMENT_VALUE #GET_GRADE_POINT_AVERAGE #GET_ID: 2 [] []
      [2014-01-07 11:47:09] app.INFO:         GRADE_POINT_AVERAGE #GET_ID: 2 [] []
      [2014-01-07 11:47:09] app.INFO:         ASSESSMENT_VALUE #GET_ASSESSMENT #GET_ID: 3 [] []
      [2014-01-07 11:47:09] app.INFO:         ASSESSMENT_VALUE #GET_VALUE: 2 [] []
      [2014-01-07 11:47:09] app.INFO:         MANAGED?  [] []
      [2014-01-07 11:47:09] app.INFO:   END OUTPUT FOR GRADE POINT AVERAGE Add Val Above - ASSESSMENT VALUE 3 [] []
      [2014-01-07 11:47:09] app.INFO: END GRADE_POINT_AVERAGE_REPOSITORY #SAVE [GPA #GET_NAME =ADD VAL ABOVE] [] []
      [2014-01-07 11:47:09] doctrine.DEBUG: "START TRANSACTION" [] []
      [2014-01-07 11:47:09] doctrine.DEBUG: INSERT INTO gpa_assessment_value (point_value, grade_point_average_id, assessment_id) VALUES (?, ?, ?) {"1":2,"2":"2","3":"3"} []
      [2014-01-07 11:47:09] doctrine.DEBUG: "ROLLBACK" [] []
      [2014-01-07 11:47:09] event.DEBUG: Notified event "kernel.exception" to listener "Symfony\Component\Security\Http\Firewall\ExceptionListener::onKernelException". [] []
      [2014-01-07 11:47:09] event.DEBUG: Notified event "kernel.exception" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelException". [] []
      [2014-01-07 11:47:09] event.DEBUG: Notified event "kernel.exception" to listener "Symfony\Component\HttpKernel\EventListener\ExceptionListener::onKernelException". [] []
      [2014-01-07 11:47:09] request.CRITICAL: Uncaught PHP Exception Doctrine\DBAL\DBALException: "An exception occurred while executing 'INSERT INTO gpa_assessment_value (point_value, grade_point_average_id, assessment_id) VALUES (?, ?, ?)' with params [2, "2", "3"]:
      
      SQLSTATE[23505]: Unique violation: 7 ERROR:  duplicate key value violates unique constraint "gpa_assessment_value_pkey"
      DETAIL:  Key (grade_point_average_id, assessment_id)=(2, 3) already exists." at /vagrant/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php line 47 {"exception":"[object] (Doctrine\\DBAL\\DBALException: An exception occurred while executing 'INSERT INTO gpa_assessment_value (point_value, grade_point_average_id, assessment_id) VALUES (?, ?, ?)' with params [2, \"2\", \"3\"]:\n\nSQLSTATE[23505]: Unique violation: 7 ERROR:  duplicate key value violates unique constraint \"gpa_assessment_value_pkey\"\nDETAIL:  Key (grade_point_average_id, assessment_id)=(2, 3) already exists. at /vagrant/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php:47, PDOException: SQLSTATE[23505]: Unique violation: 7 ERROR:  duplicate key value violates unique constraint \"gpa_assessment_value_pkey\"\nDETAIL:  Key (grade_point_average_id, assessment_id)=(2, 3) already exists. at /vagrant/vendor/doctrine/dbal/lib/Doctrine/DBAL/Statement.php:138)"} []
         

CODE

migration.sql
CREATE TABLE assessment
(
    id       bigserial NOT NULL,
    scale_id bigint    NOT NULL,
    title    varchar   NOT NULL,
    passing  boolean   NOT NULL,
    rank     int,

    PRIMARY KEY (id)
);

CREATE TABLE assessment_scale
(
    id   bigserial NOT NULL,
    name varchar   NOT NULL,

    PRIMARY KEY (id)
);

-- ...

CREATE TABLE grade_point_average
(
    id                         bigserial       NOT NULL,
    name                       varchar         NOT NULL,
    additional_credit_allowance numeric(4, 2),

    PRIMARY KEY (id)
);

-- ...

CREATE TABLE gpa_assessment_value
(
    grade_point_average_id bigint        NOT NULL,
    assessment_id          bigint        NOT NULL,
    point_value            numeric(4, 2) NOT NULL,

    PRIMARY KEY (assessment_id, grade_point_average_id),
    FOREIGN KEY (assessment_id) REFERENCES assessment,
    FOREIGN KEY (grade_point_average_id) REFERENCES grade_point_average
);
GradePointAverage.php
<?php
namespace LGSConnect\Model;

use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Column;
//...
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
use LGSConnect\Util\ConstructorArgs;
use LGSConnect\Model\GradePointAverage\AssessmentValue;
// ...

/**
 * @Entity("LGSConnect\Repository\GradePointAverageRepository")
 */
class GradePointAverage
{
    // GradePointAverage Model (owning side): a tool for evaluating a student's performance 
    // by dividing the total points earned by total credits attempted.

    use ConstructorArgs;

    /**
     * @Id
     * @GeneratedValue
     * @Column(type="bigint")
     *
     * @var int
     */
    private $id;

    // ...

    /**
     * @OneToMany(targetEntity="LGSConnect\Model\GradePointAverage\AssessmentValue", mappedBy="gradePointAverage", cascade="persist")
     *
     * @var Collection
     */
    private $assessmentValues;
    
    // ...

    /**
     * @param array $args
     */
    public function __construct(array $args = [])
    {
        $this->assessmentValues = new ArrayCollection;
        // ...
        $this->handleArgs($args);
    }
    
    // ...
    
    /**
     * @return Collection
     */
    public function getAssessmentValues()
    {
        return $this->assessmentValues;
    }

    /**
     * @param ArrayCollection $assessmentValues
     */
    public function setAssessmentValues(ArrayCollection $assessmentValues)
    {
        $this->assessmentValues = $assessmentValues;
    }

    /**
     * @param AssessmentValue $assessmentValue
     */
    public function addAssessmentValue(AssessmentValue $assessmentValue)
    {
        $this->assessmentValues->add($assessmentValue);
    }

    /**
     * @param AssessmentValue $assessmentValue
     */
    public function removeAssessmentValue(AssessmentValue $assessmentValue)
    {
        $this->assessmentValues->removeElement($assessmentValue);
    }
    
    // ...
}
AssessmentValue.php
<?php
namespace LGSConnect\Model\GradePointAverage;

use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Table;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping\JoinColumn;
use LGSConnect\Model\GradePointAverage;
use LGSConnect\Model\Assessment;
use LGSConnect\Util\ConstructorArgs;

/**
 * @Entity("LGSConnect\Repository\GradePointAverage\AssessmentValueRepository")
 * @Table("gpa_assessment_value")
 */
class AssessmentValue
{
    // AssessmentValue Model (inverse side): a number of points assigned 
    // to an Assessment by a Grade Point Average

    use ConstructorArgs;

    /**
     * @Id
     * @ManyToOne(targetEntity="LGSConnect\Model\GradePointAverage")
     */
    private $gradePointAverage;

    /**
     * @Id
     * @ManyToOne(targetEntity="LGSConnect\Model\Assessment")
     */
    private $assessment;

    /**
     * @Column("point_value")
     *
     * @var float
     */
    private $value;

    /**
     * @param array $args
     */
    public function __construct(array $args = [])
    {
        $this->handleArgs($args);
    }

    /**
     * @return GradePointAverage
     */
    public function getGradePointAverage()
    {
        return $this->gradePointAverage;
    }

    /**
     * @param GradePointAverage $gradePointAverage
     */
    public function setGradePointAverage(GradePointAverage $gradePointAverage)
    {
        $this->gradePointAverage = $gradePointAverage;
    }

    /**
     * @return Assessment
     */
    public function getAssessment()
    {
        return $this->assessment;
    }

    /**
     * @param Assessment $assessment
     */
    public function setAssessment(Assessment $assessment)
    {
        $this->assessment = $assessment;
    }

    /**
     * @return float
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * @param float $value
     */
    public function setValue($value)
    {
        $this->value = $value;
    }

    /**
     * @return AssessmentScale
     */
    public function getAssessmentScale()
    {
        return $this->assessment->getScale();
    }
}
Assessment.php
<?php
namespace LGSConnect\Model;

use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\ManyToOne;
use LGSConnect\Model\Assessment\Scale;
use LGSConnect\Util\ConstructorArgs;

/**
 * @Entity("LGSConnect\Repository\AssessmentRepository")
 */
class Assessment
{
    // Assessment (related, but unmapped): A "grade" assigned to a student 
    // for attending a course section

    use ConstructorArgs;

    /**
     * @Id
     * @GeneratedValue
     * @Column(type="bigint")
     *
     * @var int
     */
    private $id;
    
    // ...

    /**
     * @param array $args
     */
    public function __construct(array $args = [])
    {
        $this->handleArgs($args);
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }
    
    // ...
}
GradePointAverageRepository.php
<?php
namespace LGSConnect\Repository;

use Doctrine\ORM\EntityRepository;
// ...
use LGSConnect\Model\GradePointAverage;

class GradePointAverageRepository extends BaseRepository implements GradePointAverageRepositoryInterface
{
    // ...

    /**
     * @param GradePointAverage $gradePointAverage
     */
    public function save(GradePointAverage $gradePointAverage)
    {
        $this->getEntityManager()->persist($gradePointAverage);
        $this->getEntityManager()->flush();
    }
}
AssessmentValueRepository.php
<?php
namespace LGSConnect\Repository\GradePointAverage;

use Doctrine\ORM\EntityRepository;
use LGSConnect\Model\GradePointAverage\AssessmentValue;

class AssessmentValueRepository extends EntityRepository
{
    /**
     * @param AssessmentValue $assessmentValue
     */
    public function save(AssessmentValue $assessmentValue)
    {
        $this->getEntityManager()->persist($assessmentValue);
        $this->getEntityManager()->flush();
    }
}
GradePointAverageManager.php
<?php
namespace LGSConnect\Manager;

use InvalidArgumentException;
use Symfony\Component\Validator\ValidatorInterface;
use JMS\DiExtraBundle\Annotation\Service;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\SecurityExtraBundle\Annotation\PreAuthorize;
use Knp\Component\Pager\Pagination\PaginationInterface;
use LGSConnect\Repository\GradePointAverageRepository;
use LGSConnect\PaginationFactory\GradePointAveragePaginationFactoryInterface;
use LGSConnect\Model\GradePointAverage;

/**
 * @Service("grade_point_average_manager")
 */
class GradePointAverageManager
{
    /**
     * @var GradePointAverageRepository
     */
    private $gradePointAverageRepository;

    /**
     * @var GradePointAveragePaginationFactoryInterface
     */
    private $gradePointAveragePaginationFactory;

    /**
     * @var ValidatorInterface
     */
    private $validator;

    /**
     * @InjectParams
     *
     * @param GradePointAverageRepository $gradePointAverageRepository
     * @param GradePointAveragePaginationFactoryInterface $gradePointAveragePaginationFactory
     * @param ValidatorInterface $validator
     */
    public function __construct(
        GradePointAverageRepository $gradePointAverageRepository,
        GradePointAveragePaginationFactoryInterface $gradePointAveragePaginationFactory,
        ValidatorInterface $validator
    )
    {
        $this->gradePointAverageRepository = $gradePointAverageRepository;
        $this->gradePointAveragePaginationFactory = $gradePointAveragePaginationFactory;
        $this->validator = $validator;
    }

    /**
     * @PreAuthorize("isAllowedToManageTheGradePointAverage(#gradePointAverage)")
     * @param GradePointAverage $gradePointAverage
     * @throws InvalidArgumentException
     */
    public function save(GradePointAverage $gradePointAverage)
    {
        $violationList = $this->validator->validate($gradePointAverage);
        if ($violationList->count()) {
            throw new InvalidArgumentException;
        }

        $this->gradePointAverageRepository->save($gradePointAverage);
    }
}
GradePointAverageController.php
<?php
namespace LGSConnect\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Doctrine\Common\Collections\ArrayCollection;
use FOS\RestBundle\View\View;
use JMS\DiExtraBundle\Annotation\Service;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\SecurityExtraBundle\Annotation\PreAuthorize;
use Knp\Component\Pager\Pagination\PaginationInterface;
use LGSConnect\Manager\GradePointAverageManager;
use LGSConnect\Model\GradePointAverage;
use LGSConnect\Model\GradePointAverage\AssessmentValue;

/**
 * @Service("grade_point_average_controller", parent="lgs.controller.abstract")
 * @Route("/gpa", service="grade_point_average_controller")
 */
class GradePointAverageController extends BaseController
{
    /**
     * @var GradePointAverageManager
     */
    private $gradePointAverageManager;

    private $logger;

    /**
     * @InjectParams
     *
     * @param GradePointAverageManager $gradePointAverageManager
     * @param LoggerInterface $logger
     */
    public function __construct(GradePointAverageManager $gradePointAverageManager, LoggerInterface $logger)
    {
        $this->gradePointAverageManager = $gradePointAverageManager;
        $this->logger = $logger;
    }
    
    // ...

    /**
     * @Route("/{id}", name="gpa.edit", requirements={"id" = "\d+"})
     * @Method("PUT")
     *
     * @param Request $request
     * @param GradePointAverage $gpa
     * @return View
     */
    public function editAction(Request $request, GradePointAverage $gpa)
    {
        $form = $this->formFactory->createNamed(null, 'gpa', $gpa, [
            'method' => 'PUT',
        ]);
        $form->handleRequest($request);

        foreach ($gpa->getAssessmentValues() as $av) {
            $this->logger->info('GPA ID PREVALIDATE IN CONTROLLER:'.$gpa->getId());
            $this->logger->info('PREVALIDATE IN CONTROLLER ASSESSMENT VAL ASSESSMENT ID:'.$av->getAssessment()->getId());
            $this->logger->info('PREVALIDATE IN CONTROLLER ASSESSMENT VAL POINTS:'.$av->getValue());
        }

        /*
        // try reversing the order of the collection to see if that helps
        $assessmentVals = $gpa->getAssessmentValues()->toArray();
        $reversed = array_reverse($assessmentVals);
        $reversedColl = new ArrayCollection($reversed);
        $gpa->setAssessmentValues($reversedColl);
        */

        if ($form->isValid()) {
            foreach ($gpa->getAssessmentValues() as $av) {
                $this->logger->info('GPA ID PRESAVE IN CONTROLLER:'.$gpa->getId());
                $this->logger->info('PRESAVE IN CONTROLLER ASSESSMENT VAL ASSESSMENT ID:'.$av->getAssessment()->getId());
                $this->logger->info('PRESAVE IN CONTROLLER ASSESSMENT VAL POINTS:'.$av->getValue());
            }
            $this->gradePointAverageManager->save($gpa);

            return new View($gpa, 204);
        }

        return new View($form);
    }

    // ...
}
GradePointAverageType.php
<?php
namespace LGSConnect\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use JMS\DiExtraBundle\Annotation\FormType;

/**
 * @FormType
 */
class GradePointAverageType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('courses', 'entity', [
                'class' => 'Model:Course',
                'multiple' => true
            ])
            ->add('assessmentValues', 'collection', [
                'type' => 'gpa_assessment_value',
                'allow_add' => true,
                'by_reference' => false,
            ])
        ;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'gpa';
    }
}
AssessmentValueType.php
<?php
namespace LGSConnect\Form\Type\GradePointAverage;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use JMS\DiExtraBundle\Annotation\FormType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * @FormType("gpa_assessment_value")
 */
class AssessmentValueType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('assessment', 'entity', [
                'class' => 'Model:Assessment',
            ])
            ->add('value', 'number', [
                'precision' => 2,
            ])
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'LGSConnect\Model\GradePointAverage\AssessmentValue',
        ]);
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'gpa_assessment_value';
    }
}


 Comments   
Comment by Valentin Nazarov [ 23/Jan/15 ]

Any update on this issue? We've got same problem in our project (PostgreSQL 9.4, Doctrine 2.4.7)

Comment by Marco Pivetta [ 24/Jan/15 ]

Removed the "feedback required" flag.

Valentin Nazarov if there is no ticket update, well... then there is no actual update.

Somewhat related to https://github.com/doctrine/doctrine2/pull/1113

I suggest getting your hands dirty and fixing it yourself if it affects you.

Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 16/Feb/15 ]

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





[DDC-3391] RFC Allow adding extra metadata attributes Created: 13/Nov/14  Updated: 15/Feb/15

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

Type: Improvement Priority: Minor
Reporter: Gonzalo Vilaseca Assignee: Marco Pivetta
Resolution: Unresolved Votes: 1
Labels: drivers, metadata


 Description   

What I'd like to propose is a way of having custom metadata in ClassMetadata.

So the current problem is this: I want to add custom tags to doctrine metadata files, and then get this tags on a loadClassMetadata listener in order to modify the mapping.
Currently the only workaround is parsing this custom tags in the loadClassMetadata listener, going through all the files again.

I was thinking of having a new 'extra' array field in ClassMetadata, every time a driver parses a configuration, throw a new event with the read configuration (being xml, yaml...etc.). A custom listener will parse it looking for the custom tags and return an array that will be added to the 'extra' array field in ClassMetadata.

Then, on the loadClassMetadata listener we retrieve this 'extra' configuration information, and modify the mapping as we want.

Does this make sense?



 Comments   
Comment by Gonzalo Vilaseca [ 14/Nov/14 ]

Ideally instead of the 'extra' array field, it would be nice to easily extend Metadata class so that the new values are filled in the new extended Metadata class.

Comment by Christophe Coevoet [ 14/Nov/14 ]

This would be even worse. If the recommended way for extensions is to extend the Doctrine Metadata object to add their field, it means you can only use 1 extension at a time (because you cannot use the extended class of both extensions at the same time for the same object).
This is why it is much better for other libraries to store their own metadata in their own object instead of trying to put it inside the Doctrine ones.

I'm not even sure putting custom tags inside the Doctrine mapping file is the best solution. It may be better to use a separate metadata file for the mapping of the other library (just like you use a different mapping file for the Symfony validation mapping even if it applies to the same class than the Doctrine mapping for instance)

Comment by Gonzalo Vilaseca [ 14/Nov/14 ]

You're right regarding the metadata.

As for the separate files, validation in Symfony is not doctrine specific, that's why it's in a separate file. If you have a look at some doctrine extensions like ``Prezent translable`` or ``Doctrine2 behavioral extensions``, the natural location for the custom tags are the Doctrine mapping files as they are specific to doctrine, by looking at just one file you see the whole picture.

Yes, you could have your own mapping files, but then you would need to do some Symfony magic to be able to load them, and this is what would be nice to avoid.

I think of it as a way to easily extend doctrine mapping capabilities, in a 'plugin' way.

I'm currently working on a i18n bundle for Symfony, the tags I add in doctrine mapping files create associations between entities and their translations: I've had to create quite a few compiler passes for my current project to work as desired, and I see no way of abstracting this in a general way, it will need to be application specific. If I could hook into the Doctrine workflow and get those tags to populate my metadata class, that would be great, simple and reusable.

Comment by Gonzalo Vilaseca [ 19/Nov/14 ]

I've come out with another use case:
I need some custom metadata when the repository is instantiated, AFAIK there is no way of doing this right now, or is there?

Comment by Marco Pivetta [ 19/Nov/14 ]

You'd use a different metadata factory for that, specific to your use-case.
Mixing ORM mappings with the rest will just cause more coupling between the ORM and the userland use-case.

Comment by Michał Dobaczewski [ 15/Feb/15 ]

As Gonzalo Vilaseca metioned without ability to set custom metadata attributes in ClassMetadata there is no proper way to obtain custom metadata in repository class. For example popular DoctrineDxtensions written by Gediminas Morkevicius obtain custom metadata by looping throught event subscribers (https://github.com/Atlantic18/DoctrineExtensions/blob/master/lib/Gedmo/Sortable/Entity/Repository/SortableRepository.php). By the way, shame that Doctrine has no API for extensions.





[DDC-3565] "Missing value for primary key" error using JoinColumns Created: 11/Feb/15  Updated: 11/Feb/15

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

Type: Bug Priority: Minor
Reporter: Arran Walker Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: orm


 Description   

With a ManyToOne relationship to a composite foreign key and using JoinColumns, I get this error during hydration of the Branch entity when it has no associated primary Contact:

Missing value for primary key user on Contact

If there is an associated Contact, it works as expected.

I think it's related to this error on StackOverflow.

User.php
<?php

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

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

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

    public function getId()
    {
        return $this->id;
    }
}
Branch.php
<?php

use Doctrine\Common\Collections\ArrayCollection;

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

    /**
     * ORM\OneToMany(targetEntity="Contact", mappedBy="Branch", cascade={"persist", "remove"}, indexBy="user")
     */
    protected $contacts;

    /**
     * @ManyToOne(targetEntity="Contact")
     * @JoinColumns(
     *   @JoinColumn(name="primary_contact_user_id", referencedColumnName="user_id"),
     *   @JoinColumn(name="id", referencedColumnName="branch_id")
     * )
     */
    protected $primaryContact;

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

    public function addUserAsContact(User $user)
    {
        if (!$this->contacts[$user->getId()]) {
            $this->contacts[$user->getId()] = new Contact($this, $user);
        }

        return $this->contacts[$user->getId()];
    }

    public function setUserAsPrimaryContact(User $user)
    {
        $this->primaryContact = $this->addUserAsContact($user);
    }
}
Branch.php
<?php


/**
 * @Entity
 */
class Contact
{
    /**
     * @Id()
     * @ManyToOne(targetEntity="Branch")
     * @JoinColumn(name="branch_id", referencedColumnName="id", nullable=false)
     */
    protected $branch;

    /**
     * @Id()
     * @ManyToOne(targetEntity="User")
     * @JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
     */
    protected $user;

    public function __construct(Branch $branch, User $user)
    {
        $this->branch = $branch;
        $this->user   = $user;
    }

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





[DDC-3480] ORM\Embeddable does not create ManyToOne column in the database Created: 09/Jan/15  Updated: 09/Feb/15

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

Type: Bug Priority: Major
Reporter: Tomas Voslar Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: None

Issue Links:
Reference
relates to DDC-3556 [GH-1297] [DDC-3480] Docs: Embeddable... Resolved

 Description   

Following Embeddable

/**
 * @ORM\Embeddable
 */
class Address
{
    /**
     * @ORM\ManyToOne(targetEntity="Country")
     */
    protected $country;

won't save country attribute into the database table, other simple attributes (like type="text") saved normally.

    /**
     * @ORM\Embedded(class="LuciniLucini\Adsender\CommonBundle\Entity\Address")
     */
    private $address;


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

The issue seems incomplete to me: what exactly is the failure? Can you make an example?

Comment by Tomas Voslar [ 09/Jan/15 ]

Okay, I am sorry. I have main entity which includes Embeddable entity (Address), this address entity contains country attribute with ManyToOne relation, but this country is not being saved into the database table, other attributes like street (string) are being saved normally.

Comment by Tomas Voslar [ 09/Jan/15 ]

Basically it creates main entity with all fields from embeddable except country which is ManyToOne.

Comment by Marco Pivetta [ 09/Jan/15 ]

Ah, now I get it (I was probably misreading it). We don't support associations from embeddables right now: please check the test suite, but they really don't provide this functionality right now.

Comment by Tomas Voslar [ 09/Jan/15 ]

And is there any chance it will be supported in the near future? Or it's not possible?

Comment by Marco Pivetta [ 09/Jan/15 ]

It will probably not implemented for now, as embeddables (in our vision) are fitting the use-case of ValueObjects. ValueObjects are (usually) supposed to be containing serializable data, and an entity reference is not serializable data.

Comment by Tomas Voslar [ 09/Jan/15 ]

Okay, understood. So it's not good idea to use embeddables for Address entity for example, with this country as relation to another table, right? It seemed to me like best case. Thank you for the support anyway.

Comment by Marco Pivetta [ 09/Jan/15 ]

So it's not good idea to use embeddables for Address entity for example, with this country as relation to another table, right?

I'd rather just save the country identifier in the embeddable instead.

Comment by Tomas Voslar [ 09/Jan/15 ]

So you mean, instead of ManyToOne, save just id=integer (so no relation with entity)?

Comment by Marco Pivetta [ 09/Jan/15 ]

Correct: simple scalar or serializable types

Comment by Tomas Voslar [ 09/Jan/15 ]

https://github.com/doctrine/doctrine2/blob/400acad53355f24137e18d5cd55ccf6ff828cfbe/tests/Doctrine/Tests/ORM/Functional/ValueObjectsTest.php

Line 121 method testDqlOnEmbeddedObjectsField, guess I am wrong, but it seems there should be support for embeddable with relations though.

Comment by Yavin [ 11/Jan/15 ]

Hi,
if is is not supported i think an exception should be thrown when someone use association in embedded class. Now it is just silently ommited.

I found code where embedded metadata is added:
https://github.com/doctrine/doctrine2/blob/573153669c11a6f69201513831d3b8ce5e111d25/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php#L3200

Comment by Eugene Dounar [ 02/Feb/15 ]

It will probably not implemented for now, as embeddables (in our vision) are fitting the use-case of ValueObjects. ValueObjects are (usually) supposed to be containing serializable data, and an entity reference is not serializable data.

This should be explicitly stated in the documentation.

Comment by Marco Pivetta [ 02/Feb/15 ]

Eugene Dounar please send a PR to the documentation with the wording you prefer.

Comment by Eugene Dounar [ 09/Feb/15 ]

Marco Pivetta http://www.doctrine-project.org/jira/browse/DDC-3556





[DDC-3563] Wrong metadata output. One-To-Many, Bidirectional Created: 08/Feb/15  Updated: 08/Feb/15

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

Type: Bug Priority: Major
Reporter: Jason Schilling Assignee: Steve Müller
Resolution: Unresolved Votes: 1
Labels: None

Attachments: Zip Archive Data.zip    

 Description   

During observe the metadata in a One-To-Many association I've noticed that, the inversedBy value is NULL but in the annotation its assigned to something like $images (look example). I think its wrong because the EntityGenerator dont get it and dont generate the add..., remove... and get...s Method stubs or the __constructor assignment to ArrayCollections.






[DDC-3562]  Make two different join request with different join condition with Doctrine ORM Created: 06/Feb/15  Updated: 06/Feb/15

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

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

Doctrine2 symfony integration
PHP 5.5.2
MySQL 5.5.41
Linux
doctrine/annotations v1.2.3
doctrine/cache v1.4.0
doctrine/collections v1.2
doctrine/common v2.4.2
doctrine/dbal v2.5.1
doctrine/doctrine-bundle v1.3.0
doctrine/doctrine-cache-bundle v1.0.1
doctrine/inflector v1.0.1
doctrine/lexer v1.0.1
doctrine/orm v2.4.7



 Description   

I want to make two requests on an object and join a one to many relation using doctrine ORM. The first request has different condition on the joined object.
The first request should join one object, and the second one two, but both return one object when run with the same EntityManager context.

The test entity

    /**
     * TreeNode
     *
     * @ORM\Table(name="treeNode")
     */
    class TreeNode {
    	/**
    	* @var integer
    	*
    	* @ORM\Id
    	* @ORM\Column(name="id", type="integer")
    	* @ORM\GeneratedValue(strategy="AUTO")
    	*/
    	private $id;
    
    	/**
    	* @var string
    	*
    	* @ORM\Column(name="name", type="string", length=50)
    	*/
    	private $name;
    
    	/**
    	* @var \Doctrine\Common\Collections\Collection
    	*
    	* @ORM\JoinColumn(name="subdirs", nullable=true)
    	* @ORM\OneToMany(targetEntity="TestBundle\Entity\TreeNode", mappedBy="parent", cascade={"persist"})
    	*/
    	private $subdirs;
    
    	/**
    	* @var TestBundle\Entity\TreeNode
    	*
    	* @ORM\JoinColumn(name="parent", nullable=true)
    	* @ORM\ManyToOne(targetEntity="TestBundle\Entity\TreeNode", inversedBy="subdirs")
    	*/
    	private $parent;
    }

Adding some test data

    $parent = new TreeNode();
    $parent->setName('Parent');
    $parent->setParent(null);
    
    $child1 = new TreeNode();
    $child1->setName('Child1');
    $child1->setParent($parent);
    
    $child2 = new TreeNode();
    $child2->setName('Child2');
    $child2->setParent($parent);

Run the queries

    $repo = $em->getRepository('TestBundle:TreeNode');

    $qb = $repo->createQueryBuilder('t');
    $qb->innerJoin('t.subdirs', 'subnode')
    		->addSelect('subnode')
    		->where('t.name = :parentName')
    		->setParameter('childName', 'Child1')
    		->andWhere('subnode.name = :childName')
    		->setParameter('parentName', 'Parent');
    
    $result = $qb->getQuery()->getOneOrNullResult();
    var_dump($result->getSubdirs()->count()); // Gives 1, ok 
    
    
    // Get parent parent + all childs
    $qb = $repo->createQueryBuilder('t');
    $qb->innerJoin('t.subdirs', 'subnode')
    		->addSelect('subnode')
    		->where('t.name = :parentName')
    		->setParameter('parentName', 'Parent');
    $result = $qb->getQuery()->getOneOrNullResult();
    var_dump($result->getSubdirs()->count()); // Gives 1, should have been 2 !
  • The second request only returns one "subdir" object, while it should have been two.
  • If I run the second request without the first one, I get the two results, as expected. Inverting the request makes the second one return two results instead of one.
  • The correct SQL requests are run by this code, only the returned result is wrong.
  • Running `$em->clear()` between the two statements works, but I don't want to untrack my other entities.





[DDC-3558] Sequence name generation for identity strategy Created: 04/Feb/15  Updated: 05/Feb/15

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

Type: Bug Priority: Major
Reporter: Gemorroj Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: generator-strategy, identity, metadata, sequence

Attachments: PNG File Захват-1.png    

 Description   

In version 2.5 added support sequence with the strategy of identity.
But I cannot get the correct name of the sequence with the strategy of identity. With the strategy sequence produces the correct name. It is taken from the configuration sequenceName. Strategy identity name sequence will not be taken from the configuration, and is always generated is automatically (which is not working properly in my case).

see: https://github.com/doctrine/doctrine2/blob/4c68a38bd6b7d590dbfa90b2bb116129381935ce/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php#L632
the title sequence is generated automatically.

https://github.com/doctrine/doctrine2/blob/4c68a38bd6b7d590dbfa90b2bb116129381935ce/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php#L662
and in this case, it first checks its own configuration.



 Comments   
Comment by Gemorroj [ 05/Feb/15 ]

Any comments plz..?

Comment by Marco Pivetta [ 05/Feb/15 ]

Gemorroj consider writing a test case with your problem/example: I can't understand the issue as it is currently written down.

A code example is also fine.

Comment by Gemorroj [ 05/Feb/15 ]

If you use the strategy SEQUENCE, the doctrine calls the sequence specified in the configuration. And inserts a record in the database with the specified ID.
If you are using the IDENTITY strategy, doctrine inserts a record without an ID. And after a record is inserted, causes sequence (https://github.com/doctrine/dbal/blob/8cbfefe03ff2d1a2246dfb6e98b84e4b36622e6f/lib/Doctrine/DBAL/Driver/OCI8/OCI8Connection.php#L148) to learn the value of id.
But, with the IDENTITY strategy, doctrine does not know how actually called a sequence.

Comment by Marco Pivetta [ 05/Feb/15 ]

Yes, when using the IDENTITY strategy, the sequence name is not used: https://github.com/doctrine/doctrine2/blob/4c68a38bd6b7d590dbfa90b2bb116129381935ce/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php#L626-L657

That's expected behavior: what are you expecting?

Comment by Gemorroj [ 05/Feb/15 ]

If doctrine determines that the database uses the sequence, then I expect the setup sequence doctrine is taken from the configuration.
https://github.com/doctrine/doctrine2/blob/4c68a38bd6b7d590dbfa90b2bb116129381935ce/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php#L636-L638
The generated name sequence wrong for me.

Comment by Marco Pivetta [ 05/Feb/15 ]

You should rather just use the SEQUENCE strategy.

Otherwise, provide a functional test case and eventually propose a fix.





[DDC-3319] Get the converted value in convertToDatabaseValueSQL() Created: 23/Sep/14  Updated: 01/Feb/15

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

Type: Bug Priority: Minor
Reporter: Benjamin Morel Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: mapping


 Description   

I have a use case where it would be useful to get the value being converted in the convertToDatabaseValueSQL() method, not just in convertToDatabaseValue().

Take the following mapping for a Geometry type:

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        return $value->asBinary();
    }

    public function convertToDatabaseValueSQL($sqlExpr, AbstractPlatform $platform)
    {
        return sprintf('ST_GeomFromWkb(%s, %s)', $sqlExpr, 4326);
    }

In GIS-enabled databases, ST_GeomFromWkb() takes two parameters: the WKB binary representation of the geometry, and an integer representing the SRID (coordinate system) of the geometry, in this example the hardcoded value 4326.

I would be nice to have access to the value being converted in the convertToDatabaseValueSQL() as well, to be able to get the SRID from the geometry object itself, and replace the above code with something like:

    public function convertToDatabaseValueSQL($sqlExpr, AbstractPlatform $platform, $value)
    {
        return sprintf('ST_GeomFromWkb(%s, %s)', $sqlExpr, $value->srid());
    }

I don't think there is currently a technical way to do this (please correct me if I'm wrong).

Could we find a BC way to pass the value being converted to the convertToDatabaseValueSQL() method to add support for this use case?



 Comments   
Comment by Michael Lucas [ 25/Jan/15 ]

The use case which you described above would be a great addition to the convertToDatabaseValueSQL() or in the convertToDatabaseValue() be able to return an array of values which could be used in the convertToDatabaseValueSQL().

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        return array('geometry' => $value->asBinary(), 'srid'=>$value->getSRID());
    }

    public function convertToDatabaseValueSQL($sqlExpr, AbstractPlatform $platform)
    {
        return sprintf('ST_GeomFromWkb(%s, %s)', ':geometry', ':srid');
    }
Comment by Benjamin Morel [ 25/Jan/15 ]

Michael Lucas It's an interesting idea, it would work as well, although I think it might be much more complicated to implement!

Comment by Paolo Agostinetto [ 01/Feb/15 ]

It there a workaround for this? I'm probably going to use a native query.

My use case is pretty common among Postgres full-text users: I need to insert a record
using the ts_vector() function with both parameters, eg: ts_vector('english', 'This is a test'),
and both parameters has to be passed on record creation.





[DDC-3552] Code generation throws exceptions when embeddables are used Created: 30/Jan/15  Updated: 30/Jan/15

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

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


 Description   

I've created a gist showing the code you can use to reproduce the issue
https://gist.github.com/v3labs/d02244c99a87444be709

I've also included the composer.json file.

When I run php app/console doctrine:generate:entities AppBundle -v, I get the following exception:

[Symfony\Component\Debug\Exception\ContextErrorException]
Notice: Trying to get property of non-object

Exception trace:
() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php:3251
Symfony\Component\Debug\ErrorHandler->handleError() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php:3251
Doctrine\ORM\Mapping\ClassMetadataInfo->inlineEmbeddable() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php:201
Doctrine\ORM\Mapping\ClassMetadataFactory->doLoadMetadata() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:332
Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->loadMetadata() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php:78
Doctrine\ORM\Mapping\ClassMetadataFactory->loadMetadata() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:225
Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->getMetadataFor() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:115
Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->getAllMetadata() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/doctrine-bundle/Mapping/DisconnectedMetadataFactory.php:201
Doctrine\Bundle\DoctrineBundle\Mapping\DisconnectedMetadataFactory->getAllMetadata() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/doctrine-bundle/Mapping/DisconnectedMetadataFactory.php:164
Doctrine\Bundle\DoctrineBundle\Mapping\DisconnectedMetadataFactory->getMetadataForNamespace() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/doctrine-bundle/Mapping/DisconnectedMetadataFactory.php:54
Doctrine\Bundle\DoctrineBundle\Mapping\DisconnectedMetadataFactory->getBundleMetadata() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/doctrine-bundle/Command/GenerateEntitiesDoctrineCommand.php:96
Doctrine\Bundle\DoctrineBundle\Command\GenerateEntitiesDoctrineCommand->execute() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/symfony/symfony/src/Symfony/Component/Console/Command/Command.php:253
Symfony\Component\Console\Command\Command->run() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:882
Symfony\Component\Console\Application->doRunCommand() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:195
Symfony\Component\Console\Application->doRun() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php:96
Symfony\Bundle\FrameworkBundle\Console\Application->doRun() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:126
Symfony\Component\Console\Application->run() at /Users/vladislav/Sites/doctrine2.5_tests/app/console:27

If I add columnPreffix to the @Embed annotation the exception is different:

[Symfony\Component\Debug\Exception\ContextErrorException]
Catchable Fatal Error: Argument 1 passed to Doctrine\ORM\Mapping\ReflectionEmbeddedProperty::__construct() must be an instance of ReflectionP
roperty, null given, called in /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php on
line 952 and defined

Exception trace:
() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ReflectionEmbeddedProperty.php:61
Symfony\Component\Debug\ErrorHandler->handleError() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ReflectionEmbeddedProperty.php:61
Doctrine\ORM\Mapping\ReflectionEmbeddedProperty->__construct() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php:952
Doctrine\ORM\Mapping\ClassMetadataInfo->wakeupReflection() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php:721
Doctrine\ORM\Mapping\ClassMetadataFactory->wakeupReflection() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:343
Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->loadMetadata() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php:78
Doctrine\ORM\Mapping\ClassMetadataFactory->loadMetadata() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:225
Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->getMetadataFor() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:115
Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->getAllMetadata() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/doctrine-bundle/Mapping/DisconnectedMetadataFactory.php:201
Doctrine\Bundle\DoctrineBundle\Mapping\DisconnectedMetadataFactory->getAllMetadata() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/doctrine-bundle/Mapping/DisconnectedMetadataFactory.php:164
Doctrine\Bundle\DoctrineBundle\Mapping\DisconnectedMetadataFactory->getMetadataForNamespace() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/doctrine-bundle/Mapping/DisconnectedMetadataFactory.php:54
Doctrine\Bundle\DoctrineBundle\Mapping\DisconnectedMetadataFactory->getBundleMetadata() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/doctrine/doctrine-bundle/Command/GenerateEntitiesDoctrineCommand.php:96
Doctrine\Bundle\DoctrineBundle\Command\GenerateEntitiesDoctrineCommand->execute() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/symfony/symfony/src/Symfony/Component/Console/Command/Command.php:253
Symfony\Component\Console\Command\Command->run() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:882
Symfony\Component\Console\Application->doRunCommand() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:195
Symfony\Component\Console\Application->doRun() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php:96
Symfony\Bundle\FrameworkBundle\Console\Application->doRun() at /Users/vladislav/Sites/doctrine2.5_tests/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:126
Symfony\Component\Console\Application->run() at /Users/vladislav/Sites/doctrine2.5_tests/app/console:27

doctrine:generate:entities [--path="..."] [--no-backup] name

I don't think it's a Symfony specific issue. I tried using the built-in CLI tool and got the same results.



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

Yeah, this can't really work with code-gen, because embeddables require reflection to be initialized in order to operate, whereas the codegen cli-tools operate with a DisconnectedMetadataFactory, which skips reflection on purpose (it assumes that the class does not exist, therefore it does not start up reflection).

I think it's a can't fix for now.

Comment by Vladislav Veselinov [ 30/Jan/15 ]

Sorry for the formatting. I had never used jira before.

Comment by Marco Pivetta [ 30/Jan/15 ]

Vladislav Veselinov fixed the formatting, no big deal

Comment by Vladislav Veselinov [ 30/Jan/15 ]

Btw:

Changing line 947 in ClassMetadataInfo to:

if (isset($mapping['declaredField']) && $parentReflFields[$mapping['declaredField']]) {

seems to bypass the problem and the generation runs fine, but I don't know if it breaks something else. Doesn't seem like it but ... I'm not sure

Comment by Vladislav Veselinov [ 30/Jan/15 ]

Just figured out with it won't work in all cases. I'll keep digging. Thanks for the feedback!





[DDC-3548] [GH-1291] Conversion to PHP 5.4's short array syntax Created: 28/Jan/15  Updated: 28/Jan/15

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

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


 Description   

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

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

Message:

Now that the minimum PHP version is 5.4, it would be good to encourage the use of the short array syntax `[]`.
Converting the existing codebase to this syntax will promote this good practice and encourage everyone to follow it.

I have converted the codebase with [a tool](https://gist.github.com/BenMorel/6994483) I wrote for personal projects:

find doctrine2 -type f -name '*.php' -exec php short-array-syntax-converter.php {} \;

The number of changes is quite large, but I'm confident that nothing is broken, and the passing tests confirm this.



 Comments   
Comment by Doctrine Bot [ 28/Jan/15 ]

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

Comment by Doctrine Bot [ 28/Jan/15 ]

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





[DDC-2093] Doctrine Criteria does not support sorting by relationed field Created: 20/Oct/12  Updated: 28/Jan/15

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

Type: Improvement Priority: Major
Reporter: Bogdan Yurov Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   
// Here I call Criteria filter
public function getWalletsActive() {
	$criteria = Criteria::create()
		->where(Criteria::expr()->eq("isRemoved", "0"))
		->orderBy(array("currency.id" => "ASC"));
	return $this->wallets->matching($criteria);
}

// Relation
/**
 * @var Currency
 *
 * @ORM\ManyToOne(targetEntity="Currency")
 * @ORM\JoinColumns({
 * @ORM\JoinColumn(name="id_currency", referencedColumnName="id")
 * })
 */
protected $currency;

// File BasicEntityPersister.php
// This cause the problem:
if ( ! isset($this->_class->fieldMappings[$fieldName])) {
    throw ORMException::unrecognizedField($fieldName);
}
// There are no relations in $this->_class->fieldMappings at all!


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

Mark as improvement.

Comment by Liverbool [ 28/Jan/15 ]

How about this?

Comment by Marco Pivetta [ 28/Jan/15 ]

Liverbool give it a try and open a PR





[DDC-2693] Attribute/association overrides should be ignored when generating entities Created: 19/Sep/13  Updated: 27/Jan/15

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

Type: Bug Priority: Minor
Reporter: Joris van de Sande Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 9
Labels: command

Issue Links:
Duplicate
is duplicated by DDC-3109 [Doctrine\ORM\Mapping\MappingExceptio... Open

 Description   

The "orm:generate-entities" command fails when doctrine attribute and/or association overrides are used. So from the moment that you use an attribute/association override, it is implossible to use the generate entities command. I think that the solution to this problem is to ignore the overrides when generating entities.

The exception given in case of an attribute override is (this is executed within a Symfony2 project doctrine:generate:entities):

Generating entity "My\AppBundle\Entity\Job"

  [Doctrine\ORM\Mapping\MappingException]
  Invalid field override named 'value' for class 'My\AppBundle\Entity\Job'.

Exception trace:
 () at /path/to/project/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/MappingException.php:89
 Doctrine\ORM\Mapping\MappingException::invalidOverrideFieldName() at /path/to/project/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php:1922
 Doctrine\ORM\Mapping\ClassMetadataInfo->setAttributeOverride() at /path/to/project/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/YamlDriver.php:564
 Doctrine\ORM\Mapping\Driver\YamlDriver->loadMetadataForClass() at /path/to/project/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/Driver/MappingDriverChain.php:104
 Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain->loadMetadataForClass() at /path/to/project/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php:113
 Doctrine\ORM\Mapping\ClassMetadataFactory->doLoadMetadata() at /path/to/project/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:302
 Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->loadMetadata() at /path/to/project/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:212
 Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->getMetadataFor() at /path/to/project/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:112
 Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->getAllMetadata() at /path/to/project/vendor/doctrine/doctrine-bundle/Doctrine/Bundle/DoctrineBundle/Mapping/MetadataFactory.php:196
 Doctrine\Bundle\DoctrineBundle\Mapping\MetadataFactory->getAllMetadata() at /path/to/project/vendor/doctrine/doctrine-bundle/Doctrine/Bundle/DoctrineBundle/Mapping/MetadataFactory.php:176
 Doctrine\Bundle\DoctrineBundle\Mapping\MetadataFactory->getMetadataForClass() at /path/to/project/vendor/doctrine/doctrine-bundle/Doctrine/Bundle/DoctrineBundle/Mapping/MetadataFactory.php:76
 Doctrine\Bundle\DoctrineBundle\Mapping\MetadataFactory->getClassMetadata() at /path/to/project/vendor/doctrine/doctrine-bundle/Doctrine/Bundle/DoctrineBundle/Command/GenerateEntitiesDoctrineCommand.php:106
 Doctrine\Bundle\DoctrineBundle\Command\GenerateEntitiesDoctrineCommand->execute() at /path/to/project/vendor/symfony/symfony/src/Symfony/Component/Console/Command/Command.php:242
 Symfony\Component\Console\Command\Command->run() at /path/to/project/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:200
 Symfony\Component\Console\Application->doRun() at /path/to/project/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php:83
 Symfony\Bundle\FrameworkBundle\Console\Application->doRun() at /path/to/project/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:106
 Symfony\Component\Console\Application->run() at /path/to/project/app/console:19


 Comments   
Comment by Rein Baarsma [ 27/Feb/14 ]

I have the same issue and it's easy to reproduce with a clean Symfony 2 setup with FOSUserBundle.
Once you add

 * @ORM\AttributeOverrides({
 *      @ORM\AttributeOverride(name="usernameCanonical",
 *          column=@ORM\Column(
 *              name     = "username_canonical",
 *              type     = "string",
 *              length   = 255,
 *              unique   = false
 *          )
 *      )
 * })

It will properly do doc:schema:update --force
But it will fail on doc:gen:entities (YourEntity)

Comment by Andy Waterman [ 13/Aug/14 ]

Not sure I agree this is minor - might not affect many users, but it's pretty blocking if you do run into it. Any ideas on a fix?

Comment by Marco Pivetta [ 13/Aug/14 ]

Andy Waterman you are supposed to manually edit generated entities anyway

Comment by Andy Waterman [ 19/Aug/14 ]

" you are supposed to manually edit generated entities anyway"

This applies to creating new entities as well as adapting old ones. Ie. Once you use an AttributeOverride anywhere in your project, you then cannot use generate:entities anywhere else.

Comment by Marco Pivetta [ 19/Aug/14 ]

Andy Waterman yes, and you are supposed to avoid the generator after the first run.

Comment by Andy Waterman [ 20/Aug/14 ]

You really cannot use the generate:entities command to generate method stubs in ANY of your entities or new entities after the first time you run it??

If this use case works as designed without AttributeOverride in the project, but not with AttributeOverrides, then it's a bug not us doing it wrong.

Comment by Cliff Odijk [ 20/Aug/14 ]

I agree with Andy Waterman that this is a bug if it works al the time and not when you use AttributeOverrides.

Now we just temporary remove the AttributeOverrides and then generate our stubs.

Comment by Cliff Odijk [ 12/Sep/14 ]

I tried to debug the issue and found that during the gatering of the class metadata you will get the DisconnectedClassMetadataFactory which gives the StaticReflectionService for the getParentClasses it returns an empty array which should be al the parent classes of an entity. Because of this the mapping information of the parent class does not exists and can't be overwritten.

Comment by Cliff Odijk [ 12/Sep/14 ]

If I implement the following code in the getParentClasses of the StaticReflectionService it work's like a charm

if ( ! class_exists($class)) {
            throw MappingException::nonExistingClass($class);
        }

        return class_parents($class);
Comment by Enrico Schultz [ 27/Jan/15 ]

This bug has been fixed by fixing DDC-1379. If you use protected variables in your base class, the schema is created correctly and the entity generator also does not generate properties twice. When using Symfony2, just set "doctrine/orm" to "2.4@dev" in "composer.json" or wait for an upcoming release.





[DDC-3545] Persist new object failed when it works with optimistic lock Created: 27/Jan/15  Updated: 27/Jan/15

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

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

PHP 5.5



 Description   

When I was trying to persist a new object, Doctrine reported a exception:

An exception occurred while executing 'SELECT version FROM wallet WHERE user_id = ?' with params [{}]:

Catchable Fatal Error: Object of class XXXBundle\Entity\User could not be converted to string in /Users/XXX/WebSite/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php line 91

From the stack trace information, I found the original exception is:

Catchable Fatal Error: Object of class XXXBundle\Entity\User could not be converted to string

The reason is that the entity Wallet has a OneToOne mapping to entity User, and user property is also marked as primary key. When the wallet object persists, Doctrine try to fetch the new version id and use user property to find object. But Doctrine doesn't handle the primary key is an object, not a basic type. So PDO can't use a object as a query parameter.

My Entity:

class Wallet
{
    /**
     * ID
     * @var User
     *
     * @ORM\Id
     * @ORM\OneToOne(targetEntity="XXXBundle\Entity\User")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    private $user;

    /**
     * @var int
     *
     * @ORM\Version()
     * @ORM\Column(name="version", type="integer")
     */
    private $version;
}

I hope Doctrine team can solve this problem. My temporary solution is to override __toString method in User object. It is not elegant, doesn't it?



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

What exact version of the ORM is affected? Is master also behaving like this?

Comment by Max Liu [ 27/Jan/15 ]

It works well before I add version field. I didn't try with master version.





[DDC-3406] Proxy returns string instead of object Created: 21/Nov/14  Updated: 25/Jan/15

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

Type: Bug Priority: Major
Reporter: Martin Keckeis Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: orm, proxy

Issue Links:
Dependency
depends on DDC-3539 [GH-1284] #1189 DDC-3406 derived iden... Open

 Description   

I get an string in one case instead of an entity or proxy.

User -> Address -> Plant -> Hierarchy

User OneToOne Address
Address ManyToOne Plant
Plant OneToOne Hierarchy

(all are fetched as eager loading)

See PR with a test case here
https://github.com/doctrine/doctrine2/pull/1189

Reference
https://github.com/doctrine/DoctrineORMModule/issues/355



 Comments   
Comment by Doctrine Bot [ 21/Nov/14 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3535] Allow binding `Parameter` value object to statements, removing the need for explicit value and type passing Created: 24/Jan/15  Updated: 24/Jan/15

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

Type: Task Priority: Critical
Reporter: Marco Pivetta Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: binding, criteria, parameters, persister, repository, type


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

We currently have a lot of locations in the code where we use list($values, $types) = $this->computeParameters(); (pseudo-code).

This leads to a lot of code duplication and complexity.

Maybe a Parameter VO may be used instead, or a ParameterCollection with a fixed $types and a mutable $values, and with minimal internal validation.





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

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

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

Issue Links:
Reference
is referenced by DDC-2535 [GH-712] Extra lazy get for inverse s... Resolved

 Description   

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

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

Message:

This continues my previous work on making Criteria most efficient.

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

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

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



 Comments   
Comment by Doctrine Bot [ 13/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3510] [GH-1261] Add a new QuoteStrategy that automatically escape database reserved keyword Created: 16/Jan/15  Updated: 24/Jan/15

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

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


 Description   

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

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

Message:

All the upload screenshots which are used to explain what we are doing are taken from a real project developed with Mouf dependency injection framework (http://mouf-php.com/) that we use to configure the entity manager.

We wanted to create a FAQ where admin can add question/answer and use drag and drop to set the position of the question in the FAQ.

For this, at some point, in an entity, we used a protected keyword "order" in a class FAQ:

```
/**

  • @ORM\Column(type="integer", nullable=false)
  • @var int
    */
    private $order;
    ```

This fails with Doctrine. The documentation clearly explains why: http://doctrine-orm.readthedocs.org/en/latest/reference/basic-mapping.html#quoting-reserved-words

Below are a list of screenshot explaining we use the `DefaultQuoteStrategy` and the failure message we get.

![doctrineconfiguration](https://cloud.githubusercontent.com/assets/8350192/5779969/4ab5c15e-9da7-11e4-8df8-f2c718c8d66a.PNG)

In the configuration,the "quoteStrategy" setter is not set. Therefore, we use `DefaultQuoteStrategy`.

![defaultquotestrategy](https://cloud.githubusercontent.com/assets/8350192/5779977/51fe0a70-9da7-11e4-9cfa-3a86e6f8aab8.PNG)

We get this error:

![error](https://cloud.githubusercontent.com/assets/8350192/5779963/422e0bc2-9da7-11e4-902c-602a2eac7f96.PNG)
We get an error while using doctrine ORM because it doesn't auto escape protected keyword. (We can protect it manually by using ` .)

We created a new QuoteStratigy that automaticcaly escape protected keyword *only*. We just bind it via the Mouf interface:

![escapingquotestrategy](https://cloud.githubusercontent.com/assets/8350192/5780067/d9997bae-9da7-11e4-8a23-c5fa2ebaffcc.PNG)

and then the magic begins: a screenshot of the page with no error.

![succes](https://cloud.githubusercontent.com/assets/8350192/5780085/f9b597f6-9da7-11e4-85b0-cd09fb572cd9.PNG)

We would like to submit this new `EscapingQuoteStrategy` as we think it will be easier for developers to work with it, and it should not have a big performance impact (only an additional lookup in a table)



 Comments   
Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3507] [GH-1260] Added PersisterFactory to ORM. Created: 16/Jan/15  Updated: 24/Jan/15

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

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


 Description   

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

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

Message:



 Comments   
Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3481] [GH-1241] [3.0] [POC] lazy-load on a per-property base Created: 09/Jan/15  Updated: 24/Jan/15

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

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


 Description   

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

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

Message:

This is just a proof of concept that I hacked together real quick.

This changes how proxies are generated and lazy-loaded in a very radical way:

  • method calls do not cause lazy-loading
  • lazy-loading is triggered by access to non-transient properties (things that need to be lazy-loaded)
  • access to identifiers or non-mapped properties won't cause lazy-loading

Following BC breaks need to be fixed or discussed before going forward on this idea:

  • [ ] proxies don't implement `Doctrine\Common\Proxy\Proxy` anymore, but `ProxyManager\Proxy\GhostObjectInterface` (BC break, needs fixing, can be easily done with some effort)
  • [ ] `serialize($proxy)` now causes proxy initialization (probably needs fixing, as this is a major BC break)

Pending TODOs:

  • [ ] cloning a proxy is still not fully supported (requires dedicated logic in `__clone`)
  • [ ] this is just a PoC, so the code that writes proxies to disk is not yet in place


 Comments   
Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3458] [GH-1228] Fixed many small phpcs issues Created: 19/Dec/14  Updated: 24/Jan/15

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

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


 Description   

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

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

Message:

This pr fixes many small phpcs issues



 Comments   
Comment by Doctrine Bot [ 19/Dec/14 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3455] [GH-1225] Test for RuntimeException in AnnotationExporter::exportClassMetadata() Created: 19/Dec/14  Updated: 24/Jan/15

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

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


 Description   

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

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

Message:



 Comments   
Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3446] [GH-1219] Comparison like/notlike support Created: 10/Dec/14  Updated: 24/Jan/15

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

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


 Description   

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

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

Message:

Support `Comparison::LIKE` and `Comparison::NOTLIKE` additionally to doctrine/collections#50

as alternative for #1150



 Comments   
Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3444] [GH-1218] Failing test case for cascading refresh Created: 09/Dec/14  Updated: 24/Jan/15

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

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


 Description   

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

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

Message:



 Comments   
Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3441] Unidirectional ManyToOne Not Lazy Loading Created: 09/Dec/14  Updated: 24/Jan/15

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

Type: Bug Priority: Critical
Reporter: Marcus Fulbright Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: lazy-loading, proxy, public-properties, reflection

Issue Links:
Dependency
depends on DDC-3442 [GH-1217] @DDC3441 failing test cases... Open

 Description   

The Unidirectional ManyToOne association described in the docs does not lazy load correctly. The appropriate SQL will get executed, and the returned Proxy does pass type hinting for the correct class. However, the lazy loaded object always has the following properties:

  • _initializer_
  • _cloner_
  • _isInitialized_
  • lazyPropertiesDefaults

Any properties from the class definition do not show up. This is problematic when trying to get reflected properties and their values. Methods are correctly reflected.

Pull request for failing test case



 Comments   
Comment by Marcus Fulbright [ 09/Dec/14 ]

Let me know if anything else is needed.

Comment by Doctrine Bot [ 11/Dec/14 ]

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

Comment by Marco Pivetta [ 11/Dec/14 ]

Looks like a current ORM limitation (private properties lazy loading).

Related:

Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3442] [GH-1217] @DDC3441 failing test cases for the ticket Created: 09/Dec/14  Updated: 24/Jan/15

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

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

Issue Links:
Dependency
is required for DDC-3441 Unidirectional ManyToOne Not Lazy Loa... Open

 Description   

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

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

Message:

Failing test cases for the ticket DDC-3441(http://www.doctrine-project.org/jira/browse/DDC-3441)



 Comments   
Comment by Marcus Fulbright [ 09/Dec/14 ]

I didn't realize a ticket would get automatically opened when I submitted a pull request. I already put relevant details for this in DDC-3441. This is a duplicate.

Comment by Doctrine Bot [ 11/Dec/14 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3414] Joining on a table with inheritance produces badly formed ON clause Created: 26/Nov/14  Updated: 24/Jan/15

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

Type: Bug Priority: Major
Reporter: Lewis Wright Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: inheritance, joins, orm, querybuilder


 Description   

When I join on a table that uses class table inheritance, Doctrine automatically joins on the parent table, but it does it before the ON clause.

So for example, writing this DQL:

SELECT uc, c FROM MyModel\Customer c LEFT JOIN MyModel\Customer uc WITH uc.customer = c

produces:

SELECT 
 # Snipped
FROM 
  customer c0_ 
  LEFT JOIN user_customer u2_ 
  INNER JOIN base_user b1_ ON u2_.id = b1_.id ON (u2_.customer_id = c0_.id)

This syntax for the ON clause looks wrong, and fails in SQLite, so I can only assume it's the result of a bug?



 Comments   
Comment by Marco Pivetta [ 26/Nov/14 ]

Please compare the DQL you wrote by hand with the one generated by the QueryBuilder

Comment by Lewis Wright [ 26/Nov/14 ]

The issue appears not to be with just the query builder, but with the DQL version too (see the updated bug report). Would it help if I made a bare-bones doctrine application demoing the problem?

Actually, what would probably be more helpful is if I added a test to the test suite for this bug. I'll see what I can do.

Comment by Marco Pivetta [ 26/Nov/14 ]

We'd need a functional test to add to the test suite, not a demo app. Sending a pull-request with a failing test case will expose the problem immediately.

Comment by Lewis Wright [ 26/Nov/14 ]

Apologies, I should have read the contribute readme first before submitting the ticket. I've created a pull request here with the failing SQLite tests:

https://github.com/doctrine/doctrine2/pull/1194

I did put this ticket number as the PR subject, but the bot seems to have created another issue here:
http://www.doctrine-project.org/jira/browse/DDC-3415

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3415] [GH-1194] [DDC-3414] Add test for "Joining on a table with inheritance produces badly formed ON clause" Created: 26/Nov/14  Updated: 24/Jan/15

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

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


 Description   

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

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

Message:

Add a test for a bug report. The test is only simple with no assertions, since the SQL generated by Doctrine is invalid and generates an exception in SQLite.



 Comments   
Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3390] [GH-1185] add a new method that return the mapped properties Created: 12/Nov/14  Updated: 24/Jan/15

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

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


 Description   

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

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

Message:

There are some implementations that use the doctrine metadata to get the properties of a entity (DoctrineObject), and it currently uses the getFieldNames and getAssociationNames methods to retrieve and merge it.

Since the embeddables feature was added, that method will return more than one metadata for each embeddable property, and then the hydrator can never find the appropriate setter for that property.

This method allows some implementation to retrieve all mapped fields from an entity, something that can't be done using get_class_vars for example.

Of course this implementation could be done in the hydrator, but i don't think it is its responsibility to filter and merge data received from the ClassMetadata. Since you have methods to retrieve the metadata formatted as the database structure, you should also have methods to retrieve the information to the other side, in object structure.



 Comments   
Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3383] [GH-1179] Fix embeddables class metadata (work-in-progress) Created: 10/Nov/14  Updated: 24/Jan/15

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

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


 Description   

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

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

Message:

ClassMetadataInfo is returning more than one result in getFieldNames() for the embeddables properties. This method is used by DoctrineModule\Stdlib\Hydrator\DoctrineObject in the extraction process.

Since its returning a number of results equal the number of properties of the embedded object, it will never find the correct setter for the extraction and that causes that property to be removed from the extracted array.

I was able to solve the issue by hacking into the getFieldNames() for testing and merging the duplicated entries, and then the object was successfully extracted.

By digging into the code, i found out that there is a mapEmbedded(), but instead of using that for embeddeds, its using the default mapField, which may be the root cause of the problem.

  • [x] Hack into the getFieldNames() method to see if the expected solution would work
  • [x] Remove multiple class declaration in the same file from the files i'll work with
  • [x] Create a failing testcase
  • [ ] Create a solution


 Comments   
Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-1952] Add support for array parameters on the SQLFilter Created: 27/Jul/12  Updated: 24/Jan/15

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

Type: Improvement Priority: Minor
Reporter: Menno Holtkamp Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 2
Labels: None


 Description   

The SQLFilter currently only accepts string parameters which would result in SQL like:

"tableAlias.column = '$filterParameter'"

To filter an Entity that has a lifecycle, this can be usefull to filter Entities that are in a specific state, for example:

"tableAlias.state = 1"

To be able to apply the filter on an Entity that can be in multiple states, it is usefull to be able to assign an array of states using setParameter:

$allowedStates = array(1,2,3,4);
$filter->setParameter('allowedStatesParam', $allowedStates);
sprintf("tableAlias.state IN (%s)", implode(',', $this->getParameter('allowedStatesParam')));

to eventually result in:

"tableAlias.state IN (1,2,3,4)"

However, this is currently not supported, it seems to go wrong on the PDO::quote() of the parameter. The SQL works ok when setting it statically in the filter, not taking the parameter into account.

It would be nice to have support for arrays on the setParameter()



 Comments   
Comment by Petr 'PePa' Pavel [ 24/Oct/14 ]

I've just created a pull request that implements just that. The only difference is that you don't call implode on the parameter when using it.
https://github.com/doctrine/doctrine2/pull/1168

The usage would be:

$allowedStates = array(1,2,3,4);
$filter->setParameter('allowedStatesParam', $allowedStates);

$quotedList = $this->getParameter('allowedStatesParam');
"tableAlias.state IN ($quotedList)"
Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3362] [GH-1168] [DDC-1952] Support for array parameters on the SQLFilter Created: 24/Oct/14  Updated: 24/Jan/15

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

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


 Description   

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

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

Message:

Allows passing an array to SQLFilter parameter and have each item pass through quote() before turning the whole array into a comma-separated list.

For purpose see here:
http://www.doctrine-project.org/jira/browse/DDC-1952

Exception is made for types that Doctrine already recognizes as an array and stores as their derivate (array, simple_array, json_array).



 Comments   
Comment by Doctrine Bot [ 24/Oct/14 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3332] [GH-1152] Adds error message when the key is composite Created: 02/Oct/14  Updated: 24/Jan/15

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

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


 Description   

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

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

Message:

An example is:

```
SELECT u FROM User u INNER JOIN Address a ON a.user = u
```

When User has a composite key.



 Comments   
Comment by Doctrine Bot [ 02/Oct/14 ]

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

Comment by Doctrine Bot [ 17/Jan/15 ]

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

Comment by Doctrine Bot [ 17/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3328] [GH-1150] Improve Comparison::CONTAINS: allow to use custom position for % and _ wildcard characters Created: 28/Sep/14  Updated: 24/Jan/15

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

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


 Description   

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

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

Message:

This pull prevent forced wrapping of the value in to `%`
and allow to use the custom position for `%` and `_` wildcard characters in case `Comparison::CONTAINS`

Allow to build the `contains` expressions like:
```php
Criteria::expr()->contains('myField', 'some string%');
Criteria::expr()->contains('myField', '%some string');
Criteria::expr()->contains('myField', '10%');
Criteria::expr()->contains('myField', 's_m_ string');
```



 Comments   
Comment by Doctrine Bot [ 19/Oct/14 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3313] [GH-1139] Single entity flush Created: 18/Sep/14  Updated: 24/Jan/15

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

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


 Description   

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

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

Message:

The current `flush` behavior seems to be inconsistent or not well documented.



 Comments   
Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





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

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

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


 Description   

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

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

Message:

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

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

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



 Comments   
Comment by Doctrine Bot [ 11/Nov/14 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





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

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

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


 Description   

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

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

Message:

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

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

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

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

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



 Comments   
Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-2973] [GH-949] Add a default lock mode to the EntityManager Created: 10/Feb/14  Updated: 24/Jan/15

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

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


 Description   

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

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

Message:

Following [this discussion](https://groups.google.com/forum/#!topic/doctrine-dev/xKGzQcDkilE) on the mailing list, this is a first draft of a proposal to introduce a default lock mode for all entities loaded through an EntityManager.

At the moment, there is no way to set a lock mode for the following use cases:

  • Proxies obtained through `getReference()` and then initialized
  • Entities lazy-loaded through traversal of associations

This proposal introduces the idea of a default lock mode, which can be set at runtime when all reads in a transaction should be locking.

It works this way:

$em->beginTransaction();
$em->getConfiguration()->setDefaultLockMode(LockMode::PESSIMISTIC_WRITE);

// load entities from EntityManager, Repositories or DQL, traverse associations, etc.
// all these entities will be loaded with the given lock mode

$em->commit();
$em->getConfiguration()->setDefaultLockMode(null);

I have successfully tested it with the following use cases:

  • `EntityManager::find()`
  • `EntityRepository::findBy()`
  • DQL queries
  • Proxies
  • Lazy-loaded collections through OneToMany and ManyToMany associations

Before moving forward and writing proper unit tests, I'm looking for your feedback on this proposal. Is this a concept you would be happy to integrate in Doctrine?

If yes, I have a doubt as regards to where the default lock mode should be set: @Ocramius suggested to set it on the `Configuration`; this looked reasonable at first glance, and I have implemented it this way for now. It feels a tiny bit wrong though now that I see it, as I feel like the contents of the Configuration should should only be set during bootstrapping, rather than being set and reset in the controllers as in the example above. I might be wrong obviously.

My suggestion would be to move the default lock mode to the EntityManager, so that the code would become:

$em->beginTransaction();
$em->setDefaultLockMode(LockMode::PESSIMISTIC_WRITE);

Happily waiting for your feedback!



 Comments   
Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-2940] [GH-922] Two hooks for DoctrineBundle to allow ContainerFilterCollection Created: 29/Jan/14  Updated: 24/Jan/15

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

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


 Description   

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

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

Message:

Allows the DoctrineBundle to inject a ```ContainerFilterCollection``` that creates filters through dependency injection. See doctrine/DoctrineBundle#245.

Would prefer to inject the ```FilterCollection``` into the constructor of the em, but since they have a cyclic dependency I chose setter injection.



 Comments   
Comment by Doctrine Bot [ 24/Jan/15 ]

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-2785] spl_object_hash_collisions Created: 08/Nov/13  Updated: 24/Jan/15

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

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

Ubuntu 12.04



 Description   

After reading DDC-1896 and DDC-136, I'm not exactly sure if this qualifies as a bug, but anyways, here's my code to reproduce:

    public function test_hash_collision()
    {
        $counter = 0;
        do
        {
            $object = $this->create_object();
            $counter++;
            if ($counter > 1000)
            {
                //mark as skipped ? (I never hit this on PHP 5.3 at least)
                break;
            }
        }
        while ($object === false);

        // This fails with "Failed asserting that 1 matches expected 2."
        $this->assertEquals(\Doctrine\ORM\UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($object));
    }

    private function create_object()
    {
        static $hashes = array();
        $phone = new CmsPhonenumber();
        $phone->phonenumber = "1234";
        $hash = spl_object_hash($phone);
        $this->_em->persist($phone);

        if (!array_key_exists($hash, $hashes))
        {
            $hashes[$hash] = true;
            $this->_em->flush($phone);
            $this->_em->remove($phone);
            $this->_em->flush($phone);
            return false;
        }
        // Bingo! We have a new object with a recycled hash
        return $phone;
    }


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

Are you able to reproduce the test also without statics?

Comment by flack [ 08/Nov/13 ]

Yes, if I switch to $this->hashes (private $hashes = array()), the result is the same

Comment by flack [ 08/Nov/13 ]

Here's the complete test without statics & according to Doctrine CS (AFAICT):

<?php

namespace Doctrine\Tests\ORM\Functional\Ticket;

use Doctrine\Tests\Models\CMS\CmsPhonenumber;

require_once __DIR__ . '/../../../TestInit.php';

/**
 * @group DDC-2785
 */
class DDC2785Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
    public function setUp()
    {
        $this->useModelSet('cms');
        parent::setUp();
    }

    private $hashes = array();

    public function testIssue()
    {
        $counter = 0;
        do
        {
            $object = $this->createObject();
            $counter++;
            if ($counter > 1000)
            {
                //mark as skipped ? (I never hit this on PHP 5.3 at least)
                break;
            }
        }
        while ($object === false);

        $this->assertEquals(\Doctrine\ORM\UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($object));
    }

    private function createObject()
    {
        $phone = new CmsPhonenumber();
        $phone->phonenumber = "1234";
        $hash = spl_object_hash($phone);
        $this->_em->persist($phone);

        if (!array_key_exists($hash, $this->hashes))
        {
            $this->hashes[$hash] = true;
            $this->_em->flush();
            $this->_em->remove($phone);
            $this->_em->flush();
            return false;
        }

        return $phone;
    }
}

I can try and send this as a pull request, if it helps

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-2786] [GH-843] Add failing test for DDC-2785 Created: 08/Nov/13  Updated: 24/Jan/15

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

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


 Description   

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

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

Message:

Add a failing test for

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



 Comments   
Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-2524] Wrong commit order with cascade remove and double association Created: 24/Jun/13  Updated: 24/Jan/15

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

Type: Bug Priority: Major
Reporter: Matthieu Napoli Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 2
Labels: None


 Description   

We have stumbled upon a bug in a situation where a class A has the following associations to a class B:

  • A has one B (oneToOne unidirectional)
  • A has many B (oneToMany bidirectional)

Associations are with cascade remove.

We will submit a PR soon with a failing test case.

The failure is a MySQL foreign key violation exception when removing A (removals for B are executed after removals for A).



 Comments   
Comment by Valentin Claras [ 24/Jun/13 ]

Here a link to the pull request https://github.com/doctrine/doctrine2/pull/707

Comment by Matthieu Napoli [ 25/Jun/13 ]

The tests on Travis are failing as expected.

https://travis-ci.org/doctrine/doctrine2/builds/8382962

Here is the list of the queries executed for MySQL:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`doctrine_tests`.`CascadeRemoveOrderEntityG`, CONSTRAINT `FK_23681E8F99938CE5` FOREIGN KEY (`ownerO_id`) REFERENCES `CascadeRemoveOrderEntityO` (`id`))

With queries:

13. SQL: 'DELETE FROM CascadeRemoveOrderEntityO WHERE id = ?' Params: '1'
12. SQL: '"START TRANSACTION"' Params: 
11. SQL: 'SELECT t0.id AS id1, t0.ownerO_id AS ownerO_id2 FROM CascadeRemoveOrderEntityG t0 WHERE t0.ownerO_id = ?' Params: '1'
10. SQL: 'SELECT t0.id AS id1, t0.oneToOneG_id AS oneToOneG_id2 FROM CascadeRemoveOrderEntityO t0 WHERE t0.id = ?' Params: '1'
9. SQL: '"COMMIT"' Params: 
8. SQL: 'INSERT INTO CascadeRemoveOrderEntityG (ownerO_id) VALUES (?)' Params: '1'
7. SQL: 'INSERT INTO CascadeRemoveOrderEntityO (oneToOneG_id) VALUES (?)' Params: ''
6. SQL: '"START TRANSACTION"' Params: 

As you can see, the latest query causes a foreign key constraint violation (wrong order with the next, non-executed query).

Comment by Matthieu Napoli [ 25/Jun/13 ]

On the sqlite tests we can see better the order the queries are executed:

14. SQL: 'DELETE FROM CascadeRemoveOrderEntityG WHERE id = ?' Params: '1'
13. SQL: 'DELETE FROM CascadeRemoveOrderEntityO WHERE id = ?' Params: '1'
12. SQL: '"START TRANSACTION"' Params: 
11. SQL: 'SELECT t0.id AS id1, t0.ownerO_id AS ownerO_id2 FROM CascadeRemoveOrderEntityG t0 WHERE t0.ownerO_id = ?' Params: '1'
10. SQL: 'SELECT t0.id AS id1, t0.oneToOneG_id AS oneToOneG_id2 FROM CascadeRemoveOrderEntityO t0 WHERE t0.id = ?' Params: '1'
9. SQL: '"COMMIT"' Params: 
8. SQL: 'INSERT INTO CascadeRemoveOrderEntityG (ownerO_id) VALUES (?)' Params: '1'
7. SQL: 'INSERT INTO CascadeRemoveOrderEntityO (oneToOneG_id) VALUES (?)' Params: ''
6. SQL: '"START TRANSACTION"' Params: 

13 and 14 are in the wrong order.

Comment by Guilherme Blanco [ 03/Aug/13 ]

This situation is not supported and cannot be resolved within current Doctrine code.
You created a circular dependency between the entities A and B. It happened because A contains one B (oneToOne) and because B contains a pointer to A as part of oneToMany association.
That way, you'll always have a foreign key constraint issue from RDBMS, no matter which entity you try to remove first.

Because of that, I'mm marking this ticket as "can't fix".

Comment by Matthieu Napoli [ 05/Aug/13 ]

Guilherme Blanco I see what you mean, but the case we submitted is with a nullable foreign key. So the operation is permitted by the RDBMS.

A has one B (nullable oneToOne), and B has a pointer to A (manyToOne, not nullable).

As I said for the query log, B should be removed first, which is not the case (see above, line 13 and 14 should be inversed).

So this is fixable on the Doctrine side if I'm not mistaken.

Comment by Benjamin Eberlei [ 03/Jan/14 ]

Matthieu Napoli is this fixed with your DDC-2775 PR?

Comment by Matthieu Napoli [ 15/Jan/14 ]

Just for clarity (I answered this question in the pull request): no this is not fixed (see https://github.com/doctrine/doctrine2/pull/707#issuecomment-31564035).

Comment by Benjamin Morel [ 04/Dec/14 ]

Just encountered what I believe to be the same bug, without any kind of circular dependency:

class A {
    /**
     * @ORM\OneToMany(targetEntity="B", mappedBy="a", indexBy="x", cascade={"all"}, orphanRemoval=true)
     */
    private $b;

    ...
}

class B {
    /*
     * @ORM\ManyToOne(targetEntity="A", inversedBy="b")
     * @ORM\JoinColumn(name="aid", referencedColumnName="id", nullable=false, onDelete="CASCADE")
     */
    private $a;

    ...
}

The following operations in A:

$this->b->clear();
$this->b->add(new B());

Result in the following SQL commands:

INSERT INTO B ...
DELETE FROM B ...

This is always the wrong commit order, and is doomed to fail when you have unique constraints in the B table.

Comment by Maxim Kapkaev [ 19/Dec/14 ]

Another situation without circular dependency:

class Entity
{
    /**
     * @ORM\OneToMany(targetEntity="Picture", mappedBy="entity", fetch="EXTRA_LAZY", cascade={"all"}, orphanRemoval=true)
     * @ORM\OrderBy({"position" = "ASC"})
     */
    protected $pictures = array();
} 

class Pictures {
    /**
     * @ORM\Column(type="string", length=1024, unique = true)
     */
    protected $file;
}
$hotel->setPictures($picturesArray);
$em->flush();
$hotel->getPictures()->clear();
$hotel->setPictures($somePictureUpdatedArray);
$em->flush();
Unique violation: 7 ERROR:  duplicate key value violates unique constraint "uniq_8f7c2fc08c9f3610"

Why we can't invoke entity deletions method (executeDeletions, UnitOfWork#commit) before executeInserts?
https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/UnitOfWork.php#L385-L388
There is another way?

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-2363] Duplicated record with orphanRemoval and proxy Created: 22/Mar/13  Updated: 24/Jan/15

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

Type: Bug Priority: Major
Reporter: Manuele Menozzi Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: orphanRemoval, proxy
Environment:

Tested both Mac OS X and Ubuntu


Issue Links:
Duplicate
is duplicated by DDC-2364 [GH-625] [DDC-2363] Duplicated record... Open

 Description   

There is a problem that causes duplicate records are created when EntityManager has to remove an entity due to orphanRemoval. The problem occurs only with a double flush and referred object is a proxy.

I'm trying to submit a pull request for this ticket. Please, stand by.



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

Hey Manuele Menozzi, do you remember if this has been fixed? Are you still able to reproduce the problem?

Comment by Manuele Menozzi [ 27/Mar/14 ]

Hi Marco,
I made a PR (https://github.com/doctrine/doctrine2/pull/625) with an automated test that reproduce the problem. I just ran this test over latest version of doctrine2 and it's still failed. So, the problem has not be fixed and I (or you) can reproduce it easily.

Let me know if I can help you somehow.

Comment by Marco Pivetta [ 27/Mar/14 ]

Thanks, didn't see it!

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-2364] [GH-625] [DDC-2363] Duplicated record with orphanRemoval and proxy Created: 22/Mar/13  Updated: 24/Jan/15

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

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

Issue Links:
Duplicate
duplicates DDC-2363 Duplicated record with orphanRemoval ... Awaiting Feedback

 Description   

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

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

Message:

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



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

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

Comment by Doctrine Bot [ 24/Jan/15 ]

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





[DDC-3527] Provide a method to retrieve exactly one entity out of entity repository Created: 20/Jan/15  Updated: 22/Jan/15

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

Type: Improvement Priority: Minor
Reporter: Dominik D Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Hello,

currently we have EntityRepository::findOneBy() method for retrieving a single or none entities out of an EntityRepository. It would be very useful, if there was a method which retrieves exactly one entity or throws NonUniqueResultException in case of multiple records returned or NoResultException in case of zero results returned (just like Query::getSingleResult() currently does).

Very often I find myself creating custom repositories for a couple of ::findOneByOrThrow() methods only. Needless to say it's quite mundane to do. The bodies of such methods follows the same pattern:

1. Query the EntityRepository using EntityRepository::findOneBy().
2. If the result is null, then throw an Exception.
3. Return the result.

It'd be very nice to have it out-of-the-box in the base EntityRepository.

Thanks.



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

We actually want to reduce the repository API, not expand it...

Comment by Dominik D [ 21/Jan/15 ]

Wow, ok. I guess you've got good reasons for it and I shouldn't try to convince you, that having methods for most common use cases out of the box is quite convenient?

If yes, then fine. I can create a common EntityRepository subclass for myself and put any helper methods I want there. This would at least cut down on the code duplication in my codebase.

If what you say is final, then we can close this ticket.

Cheers.

Comment by Marco Pivetta [ 22/Jan/15 ]

I guess you've got good reasons for it and I shouldn't try to convince you, that having methods for most common use cases out of the box is quite convenient?

The main problem is that adding API methods to repositories forces any subclasses to also apply eventual filtering logic to those as well.

Other than that, it's merely a question of interface segregation: the current API is hardly maintainable if we assume that many developers subclassed the EntityRepository class, therefore we should keep it locked until 3.x.

I'll actually mark this issue for 3.0 and defer discussion till then.

Comment by Dominik D [ 22/Jan/15 ]

Ok, thanks.





[DDC-2170] Decorator base classes for query related objects Created: 26/Nov/12  Updated: 22/Jan/15

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

Type: New Feature Priority: Major
Reporter: Lars Strojny Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Doctrine\ORM\Query should not be directly extendable but it would be nice to decorate query objects and add additional methods. Use cases are e.g. doctrine-fun (see https://github.com/lstrojny/doctrine-fun/blob/master/src/Doctrine/Fun/Query.php) or even cases where users want to add domain specific methods. As Doctrine\ORM\Query is final it is not so easy to decorate correctly. I would propose:

  • Add a new interfaces: Doctrine\ORM\QueryInterface that provides a contract for all methods Doctrine\ORM\Query provides
  • Add a decorator base class Doctrine\ORM\QueryDecorator as an extension point
  • Some for NativeQuery and QueryBuilder


 Comments   
Comment by Lars Strojny [ 26/Nov/12 ]

Related:

Comment by Aurimas Niekis [ 21/Jan/15 ]

Any changes on this?

Comment by Marco Pivetta [ 22/Jan/15 ]

The EntityManagerInterface now allows producing custom query objects: just requires a custom createQuery or createQueryBuilder API.

Comment by Aurimas Niekis [ 22/Jan/15 ]

Yes, but you can't extend `Doctrine\ORM\Query` object, and many places expects `Doctrine\ORM\Query` not your custom query object

Comment by Marco Pivetta [ 22/Jan/15 ]

Oh, I see what you mean.

Yes, those still require patching, so I suggest getting your hands dirty and trying with a pull request





[DDC-3525] Exception "The column id must be mapped to a field in class" when associationKey used Created: 20/Jan/15  Updated: 21/Jan/15

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

Type: Bug Priority: Major
Reporter: Ilya Antipenko Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: associationKey, foreign-key

Attachments: Text File foreign-key.log    

 Description   

I have issue when I use "associationKey"

I create test repo for reproduce this issue:
https://github.com/aivus/symfony2-foreign-bug

1. composer install
2. Set DB parameters in app/config/parameters.yml and create DB
3. php app/console doctrine:schema:create --force
4. php app/console server:run
5. Load fixtures: http://127.0.0.1:8000/app/loadFixture
6. Try to get list: http://127.0.0.1:8000/app_dev.php/admin/app/app/order/list

I make workaround, which works for me (https://github.com/aivus/doctrine2/commit/8461111e8aea98d02175f3642870a689d446beef), but I'm not sure about it



 Comments   
Comment by Ilya Antipenko [ 21/Jan/15 ]

Add stacktrace





[DDC-3215] wrong quotation Created: 16/Jul/14  Updated: 20/Jan/15

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

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


 Description   

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

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

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

DELETE FROM test WHERE test_id = '6'

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

DELETE FROM test WHERE test_id = 6

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

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

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

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

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


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

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

Comment by revrev [ 16/Jul/14 ]

i try to describe what i have done

i have an Entity with:

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

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

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

when i now clear the Data

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

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

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

Comment by Marco Pivetta [ 16/Jul/14 ]

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

Comment by revrev [ 16/Jul/14 ]

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

i don´t set messe_id here

Comment by Marco Pivetta [ 16/Jul/14 ]

Can you var_dump the Base\Entities\Messe instance?

Comment by revrev [ 16/Jul/14 ]

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

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


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

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

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

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

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

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

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

Comment by Marco Pivetta [ 17/Jul/14 ]

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

Comment by Mathias Dietrich [ 20/Jan/15 ]

@Marco Pivetta:

I was affected by exact the same issue. Even when running git master at the beginning of last week, it was still broken.
Today I retestet. Luckily your latest commits (from beginning with: 445798ed46291f2639b3657142bd2f934d1be8a6) to the BasicEntityPersister seemed fixed it.

@revrev:
Could you please retest your example? This bug might be fixed. Thx.





[DDC-3512] Redesign ClassMetadata API as ValueObject based (for type-safety and self-documentation) Created: 17/Jan/15  Updated: 18/Jan/15

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

Type: Improvement Priority: Critical
Reporter: Marco Pivetta Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: classmetadatafactory, cleanup, metadata, performance, type-safety

Issue Links:
Reference
relates to DDC-3503 [GH-1257] Resolve target entity also ... Resolved

 Description   

The current ClassMetadata API is based on a lot of array juggling (for performance reasons).

While that was understandable with PHP 5.3, all the array access operations are currently:

  • slowing things down
  • making the code very hard to read/understand

I suggest re-coding the ClassMetadata internals (public properties and such) so that well-described properties are defined.

Additionally, as a bonus, we'd get a performance boost by just moving all the class-alias and type resolution logic from the runtime into the ClassMetadataFactory (or similar) API, saving tons of performance at every run.

In pseudo-logic, what I'd like to achieve with DDC-3512 is:

  • base metadata is loaded from the mapping driver
  • onLoadMetadata event is fired for each loaded metadata instance
  • metadata is completed by the ClassMetadataFactory logic
  • onCompleteMetadata event is fired for each loaded metadata instance

This would make metadata manipulation from events a bit messier (user needs to know which value to change during which event), but would allow using better constrained metadata structures in future, and that would disallow mistakes during event listeners execution as well (internal validation).






[DDC-349] Add support for specifying precedence in joins in DQL Created: 18/Feb/10  Updated: 17/Jan/15

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

Type: Improvement Priority: Major
Reporter: Dennis Verspuij Assignee: Roman S. Borschel
Resolution: Unresolved Votes: 1
Labels: None

Attachments: Text File DDC349Test.patch    
Issue Links:
Duplicate
is duplicated by DDC-1256 Generated SQL error with DQL WITH and... Resolved
Reference
is referenced by DDC-3500 [GH-1254] Fix applying ON/WITH condit... Resolved

 Description   

This request is in followup to my doctrine-user message "Doctrine 2.0: Nested joins'.
I am a bit surprised by the responses in that defining precedences in joins by placing parenthesis around join expressions is not well-known. Although not in the original SQL92 specification it is a major and important feature offered by all the RDBMS's that Doctrine 2 supports, and oftenly performs better than using subselects or alike. Doctrine 1 did not support it, but imho Doctrine 2 should support it to be a mature allround ORM.

As a short example the following is a SQL statement with a nested join, where the nesting is absolutely necessary to return only a's together with either both b's and c's or no b's and c's at all:

SELECT *
FROM a A
LEFT JOIN (
b B
INNER JOIN c C ON C.b_id = B.id
) ON B.a_id = A.id

In order for Doctrine 2 to support this the BNF should be something like:
Join ::= ["LEFT" ["OUTER"] | "INNER"] "JOIN" ( "(" JoinAssociationPathExpression ["AS"] AliasIdentificationVariable Join ")" | JoinAssociationPathExpression ["AS"] AliasIdentificationVariable ) [("ON" | "WITH") ConditionalExpression]
instead of the current:
Join ::= ["LEFT" ["OUTER"] | "INNER"] "JOIN" JoinAssociationPathExpression ["AS"] AliasIdentificationVariable [("ON" | "WITH") ConditionalExpression]

This would allow DQL like:

SELECT A, B, C
FROM a A
LEFT JOIN (
A.b B
INNER JOIN B.c C
) WITH B.something = 'value' AND C.something = 'othervalue'

What further needs to be done is that the DQL parser loosly couples the ConditionalExpression to any of the previously parsed JoinAssociationPathExpression's instead of tieing it explicitely to the JoinAssociationPathExpression that preceedes it according to the old BNF notation. The new BNF should however not require any changes to the hydrator. Therefore I have the feeling that improving the DQL parser for nested joins does not require extensive work, while the benefit of running these kind of queries is considerable.

As an extra substantiation here are links to (BNF) FROM clause documentations of the RDBMS's that Doctrine 2 supports, they all show support for nested joins:
MySQL: http://dev.mysql.com/doc/refman/5.0/en/join.html
PostgreSQL: http://www.postgresql.org/docs/8.4/interactive/sql-select.html#SQL-FROM and http://www.postgresql.org/docs/8.1/interactive/explicit-joins.html
MSSQL: http://msdn.microsoft.com/en-us/library/ms177634.aspx
Oracle: http://download.oracle.com/docs/cd/E11882_01/server.112/e10592/statements_10002.htm#CHDDCHGF
SQLite: http://www.sqlite.org/syntaxdiagrams.html#single-source

I surely hope you will consider implementing this improvement because it would save me and others from the hassle of writing raw SQL queries or executing multiple (thus slow) queries in DQL for doing the same. Thanks anyway for the great product so far!



 Comments   
Comment by Guilherme Blanco [ 13/Apr/10 ]

This seems to be a valid issue to me.

This implementation is the actual solution to associations retrieval that are inherited (type joined).

Example:

/** Joined */
class Base {}

class Foo extends Base {}

class Bar {
    public $foo;
}

// This causes the CTI to link as INNER JOIN, which makes the result become 0
// il if you have no Foo's defined (although it should ignore this)
$q = $this->_em->createQuery('SELECT b, f FROM Bar b LEFT JOIN b.foo f'); 
Comment by Roman S. Borschel [ 13/Apr/10 ]

Yes, this is a possible solution for DDC-512 but on the SQL level. I still don't see this as appropriate for DQL, it just doesnt make sense to me, DQL joins object associations, there is no precedence.

Comment by Roman S. Borschel [ 13/Apr/10 ]

So, no, this has nothing to do with DDC-512. DDC-512 can even be fixed differently as outlined in my comments there.

Comment by Roman S. Borschel [ 13/Apr/10 ]

On a side note I would still like to know/see the following for this issue:

  • Some realisitic DQL examples where this feature would be essential, i.e. there is no other way to do it.
    This also means explaining what the impact on the resulting object graph is and why it makes sense.
  • Which other ORMs support this on the OQL/Criteria level?

So far, my stance on this issue is:

1) It doesnt make sense (semantically) in DQL
2) Its rarely needed
3) When you really need it you can use a NativeQuery anyway and use this nesting in SQL, where it probably belongs and makes more sense
4) It would (unnecessarily) complicate DQL

Thus I am currently leaning towards "Wont fix" for this issue.

Comment by Dennis Verspuij [ 13/Apr/10 ]

Hi Roman. I understand your doubts, and I have been breaking my head over
creating a realistic example the last few hours that would hopefully convince
you for implementing this feature. But actually I cannot find one that you wouldn't
consider to be trivial. I do have a number of very complex optimized queries written
for sportskickoff dot com (using Doctrine 1.2) but they are probably hard to understand
because they may not be selfdescribing. Below is one example literally ripped from
the application. Still they often can be broken down to my example query in this
ticket's description, but applied grouping, additional other joins on the root component
and/or other criteria made them impossible to rewrite using subselects or choosing
another root component. Most often they just performed way best using the nested
syntax and saved me a number of additional queries.

SELECT A.id, A.username, A.balance, COALESCE(SUM(B.stake), 0) AS sumstake, COUNT(B.id) AS nrbets
FROM account A
LEFT JOIN (
bet B
INNER JOIN game G ON G.id = :GAMEID AND B.timestampcompletion BETWEEN G.timestampstart AND G.timestampend
) ON B.accountid = A.id AND B.timestampcompletion IS NOT NULL
WHERE A.Status & :ACTIVEORDISQUALIFIED = :ACTIVE
GROUP BY A.id, A.username, A.balance
ORDER BY A.balance DESC, sumstake ASC, nrbets ASC, A.username ASC

But let's put it another way. I would also like this feature to be supported in DQL
because I just do not want to use native queries. Why would I want to use native
queries if it can be done using DQL? In DQL I work with class names and field
names, and they may differ from the underlying table and column names. Doctrine
takes care of that mapping based on my schema/annotations and I do not
have to "know" these mappings. In native queries I suddenly do have to "know"
these mappings. I use Doctrine because it makes my application portable and
enables me to work with my database in an OOP way like I do in my model,
abstracting things. The need for native queries partly reverts the benefits Doctrine
offers in the first place.

Btw, I recall to have successfully used the nested join syntax in HQL (.NET Hibernate)
but I cannot find examples on the web or a BNF notation.

Furthermore, in reply to your stances:
1) It indeed doesnt make sense (semantically) in DQL, it only makes the result
set different, but not the way data is hydrated into objects;
2) Its indeed rarely needed for inserting, updating and populating basic lists but
it allows you to better select what combinations of associated rows are joined
and which not in more optimized queries without having to use native queries,
or because they perform better than using subseletcs and alike.
3) Not having to use native queries is just an extra reason for using Doctrine and
maintains the abstraction the ORM provides througout on'es whole application
4) Why would it complicate DQL, if people do not know about or understand
the feature it wouldn't matter because not using parenthesises is the default
way to specify joins?

Well, this is it, can't find any more words to promote and make you enthusiastic.... lol.

Comment by Dennis Verspuij [ 13/Apr/10 ]

Ok, I have not given up yet... , here's a "stupid" example.

Imagine a book store that sells books of various authors and keeps track of those sales.
Let's say you would have an admin page that lists all authors, and for each author
its also shows the books and their sales dates since january 1st, but only for those
books that were actually sold and contain an A in its name. An optimized SQL query
to fetch all the information at once would be something like:

SELECT A., B., S.*
FROM author A
LEFT JOIN (
book B
INNER JOIN sale S ON S.book_id = B.id AND S.dt >= '2010-01-01'
) ON B.author_id = A.id AND A.name LIKE '%A%'

In DQL it would then be something like:

SELECT A., B., S.*
FROM author A
LEFT JOIN (
book B
INNER JOIN sale S WITH S.dt >= '2010-01-01'
) WITH A.name LIKE '%A%'

If the database would contain thousands of books, but sales for just a
few books, this will definitely perform better than using subselects.
Off course one would like to fetch array graphs instead of objects for
further optimization, but this hopefully shows my point.

I have attached a test casefor a similar query, though without the additional
join constraints for clarity. I surely hope you can consider it.

One last note, you shouldn't be afraid that nesting joins is not in the
ansi SQL spec. Select queries are about record sets and products
between these sets, tables are just the basic means of providing record
sets to the query. This is an important terminological difference to think about.
Specifying precedence with parenthesis around joins is a logical and
natural evolution of the ansi sql standard. For example views are a good
proof of this concept, I could define book B INNER JOIN sale S as a view
and LEFT JOIN that to authors to get effectively the same result
set as the above example. The database server would internally perform the
same query (though may additionally take indexes on the view into account).
That said, rdbm's that support this syntax would certainly never drop the
feature, as its not a feature but just plain logical and smart querying!

P.S. I had a hard time finding out how to run the test cases, I could not find
it in the Doctrine 2 documentation, development wiki, cookbook or any other
place, while finally it was as easy as running phpunit Doctrine_Tests_AllTests
from within the tests/ directory, or just phpunit Doctrine_Tests_ORM_Functional_Ticket_DDC349Test
for my test. Could you please add some info about this somewhere, it might
save others some googling.

Comment by Dennis Verspuij [ 13/Apr/10 ]

Test case as SVN patch using a parenthesized join.
Just remove the parenthesises from the query to have it fail...

Comment by Roman S. Borschel [ 29/May/10 ]

@"The need for native queries partly reverts the benefits Doctrine offers in the first place."

That is something I hugely disagree with. Neither SQL abstraction, nor database vendor independence is the main purpose of an ORM like Doctrine 2.
It is the state management of your objects, the transparent change tracking, lazy-loading and synchronization of the object state with the database state and nothing of this gets lost when using native queries.

We could rip out DQL and any other querying mechanism except a basic find() (and lazy-loading, of course), only providing the native query facility and even only supporting MySQL and would still retain all the core ORM functionality.

NativeQuery is one of the best and core "features" of the project. It is even the foundation for DQL. A DQL query is nothing more than an additional (beautiful) abstraction but what comes out is a native query + a ResultSetMapping, the same thing you can build yourself in the first place, even using the mapping metadata to construct the query. Nothing forces you to hardcode table and column names in native queries if you don't want that. Just use the mapping metadata, DQL does the same.

SQL abstraction and database vendor independence is icing on the cake, not the heart of the ORM.





[DDC-3416] using getArrayResult and foreach with reference get a string at the end Created: 26/Nov/14  Updated: 17/Jan/15

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

Type: Bug Priority: Minor
Reporter: sysko Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: None
Environment:

doctrine2 alone, not inside symfony or any framework



 Description   

This bug is quite weird so let me explain it

I have 2 Entity

Category (language independant information)

CategoryDescription (language dependant category 1 -> N categoryDescription)

when i do

        $categories = $this->createQueryBuilder('Entity\Category')
            ->select('c')
            ->distinct()
            ->from('Entity\Category', 'c')
            ->getQuery()
            ->getArrayResult();
        ;

        foreach ($categories as &$category) {
            var_dump($category);
            $plop = $category['id'];
        }

I will get the last element of the array as a string instead of an array
and that string being the value of the column "name" of the last CategoryDescription in my database

using a normal foreach without reference does not trigger the bug
using getResult also does not trigger the bug

if needed and someone guide me I can try to furnish a "minimal code" to reproduce the issue



 Comments   
Comment by Claudio [ 17/Jan/15 ]

Does CategoryDescription contain a __toString() method?





[DDC-2570] Doctrine CLI Tools - Clear All Cache Created: 24/Jul/13  Updated: 17/Jan/15

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM, Tools
Affects Version/s: 2.3.4
Fix Version/s: 2.x

Type: Improvement Priority: Minor
Reporter: Frederick Marcoux Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: Cli, cache, orm


 Description   

It would be nice to be able to clear all cache one shot instead of clearing them one after one...

Like this:

root$ ./doctrine orm:clear-cache:all

Instead of:

root$ ./doctrine orm:clear-cache:metadata
root$ ./doctrine orm:clear-cache:result
root$ ./doctrine orm:clear-cache:query






[DDC-1599] OnFlush event in transaction Created: 14/Jan/12  Updated: 17/Jan/15

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

Type: Improvement Priority: Major
Reporter: Gediminas Morkevicius Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 3
Labels: None


 Description   

Is there any particular reason why onFlush event is not triggered when the transaction is allready open? https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/UnitOfWork.php#L290 It would help a lot developing listeners since this event is the mostly used one and since theres preFlush now it seems a logical solution if onFlush would be a start of transaction in general



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

onFluish is not the start of a transaction. It has nothing to do with this.

Comment by Marco Pivetta [ 31/Mar/12 ]

Is a third event needed? Or is this to be marked as "won't fix"?

Comment by Benjamin Eberlei [ 31/Mar/12 ]

Maybe onBeginTransaction, onCommit and onRollback.

However since you can start transactions manually using $em->beginTransaction(), the Flush events are somehwat independent of transactions anyways.

Comment by Gediminas Morkevicius [ 31/Mar/12 ]

Well, user can start transaction anytime, but the fact is that if we think ORM we do not know nothing about the database. we just persist and flush objects.

Yes I think these would be very useful, from how I see it, if you use event listeners, is:

loadClassMetadata: you can apply extra mapping

onFlush: you can modify entity changesets, or persist recalculate new ones, without triggering the database, since it is not used to begin the database modifications yet.

onBeginTransaction: could use the database modifications keeping in sync the entity changesets. the thing about this event is that usually in behavioral way atomic updates are required. for example nestedset tree sync lft rgt columns, sortable sync the sort index, materialized path, all these requires atomic updates, and the best place is the start of transaction.

onCommit: could be useful to execute right before commit, finalizing database modifications could be done.

onRollback: this one is really something, since if you go far, there might be something like files uploaded during the entity processing, and you may want to remove them if transaction fails.

Comment by Guilherme Blanco [ 21/May/12 ]

This situation was barely documented here: http://www.doctrine-project.org/jira/browse/DDC-1443

We need a better Transaction API that completely fixes the computation of changesets and also allow more fine grained control over Entities and their corresponding information.

I'd postpone this one until 3.0.





[DDC-1738] Allow multiple Generators per class Created: 29/Mar/12  Updated: 17/Jan/15

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

Type: Improvement Priority: Major
Reporter: Guilherme Blanco Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

We should be able to support multiple generators per class.
When doing partition per table, the partitioned column must be part of PK, which may enter in our limitation.

Currently we only support 1 generator per class.






[DDC-1852] Doctrine\ORM\Tools\SchemaValidator should check validity of lifecycle callbacks Created: 04/Jun/12  Updated: 17/Jan/15

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

Type: Improvement Priority: Major
Reporter: Marco Pivetta Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

The schema validator should analyze mapped lifecycle callbacks and:

a) if some lifecycle callbacks were defined, but no @HasLifecycleCallbacks annotation/mapping was set, warn the user
b) if some lifecycle callbacks were defined, but methods are not public, warn the user



 Comments   
Comment by Marco Pivetta [ 04/Jun/12 ]

Existing PR at https://github.com/doctrine/doctrine2/pull/361





[DDC-1963] Remove by-ref access to changeset in lifecycle event args Created: 31/Jul/12  Updated: 17/Jan/15

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

Type: Improvement Priority: Major
Reporter: Marco Pivetta Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: None


 Description   

UoW currently passes computed changesets to lifecycle event args byref. This has to be changed to force users to use UoW public API to modify changesets instead.






[DDC-2390] Remove Parser and SQLWalker dependency on Query Created: 04/Apr/13  Updated: 17/Jan/15

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

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


 Description   

Query is too powerful to be available in Parser and SQLWalker, because it may lead to accessing data that changes on subsequent runs of a query that is cached.

Idea is to introduce a MetadataBag that contains only the values that are allowed to be accessed.






[DDC-3511] Temporarily change fetch mode in DQL for toMany relations Created: 16/Jan/15  Updated: 16/Jan/15

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

Type: New Feature Priority: Major
Reporter: Filip Procházka Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: dql, eager, fetch-mode, query


 Description   

This would be a major improvement. I can't seem to find the issue for this. Is this even planned?

http://docs.doctrine-project.org/en/latest/reference/dql-doctrine-query-language.html#temporarily-change-fetch-mode-in-dql

I might be able to find some time to work on this in February, if nobody else is going to.



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

You might want to wait for the persisters to stabilize with 2.5





[DDC-3349] Possibility to override order of fields of composite ID produced by Mapping Created: 13/Oct/14  Updated: 16/Jan/15

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

Type: New Feature Priority: Major
Reporter: tiger-seo Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: mapping

Issue Links:
Reference
relates to DDC-3352 [GH-1162] DDC-3349: Possibility to ov... Resolved

 Description   

So, the problem is when the one needs to use association key in composite identifier; they are added in the end of the identifier array, which is clearly not always suitable in regards to performance.
For example, following mapping:

Acme\DemoBundle\Entity\PageLocalFans:
    type: entity
    id:
        date:
            type: date
        page:
            associationKey: true
        countryCode:
            type: string
            length: 2
    fields:
        fans:
            type: integer
    manyToOne:
        page:
            targetEntity: Page
            joinColumn:
                name: page_id
                referencedColumnName: id
                onDelete: CASCADE

will turn into sql as:

CREATE TABLE page_local_fans (
  date         DATE       NOT NULL,
  country_code VARCHAR(2) NOT NULL,
  page_id      INT        NOT NULL,
  fans         INT        NOT NULL,
  INDEX IDX_7391EB36C4663E4 (page_id),
  PRIMARY KEY (date, country_code, page_id)
) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;

and there is no way to change the order of the primary from

PRIMARY KEY (date, country_code, page_id)

to

PRIMARY KEY (date, page_id, country_code)


 Comments   
Comment by tiger-seo [ 14/Oct/14 ]

i've done the PR for this, pls see https://github.com/doctrine/doctrine2/pull/1162

Comment by Doctrine Bot [ 17/Oct/14 ]

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

Comment by Doctrine Bot [ 16/Jan/15 ]

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





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

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

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


 Description   

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

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

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



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

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

Comment by Benno Eggnauer [ 17/Jun/14 ]

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

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

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

Comment by Marco Pivetta [ 17/Jun/14 ]

Benno Eggnauer can you eventually provide a pull request?

Comment by James Blizzard [ 01/Dec/14 ]

I would just like to say that we're having exactly the same issue. I'd love some method (official or not) of having filters being taken into account in this situation.

Comment by Guglielmo Carandente [ 16/Jan/15 ]

I have the same problem when is generated QueryCacheId It consider only the name of active filters and not the value of the filter
This is the code at line 646 of class \Doctrine\ORM\Query
protected function _getQueryCacheId()

{ ksort($this->_hints); return md5( $this->getDql() . var_export($this->_hints, true) . ($this->_em->hasFilters() ? $this->_em->getFilters()->getHash() : '') . '&firstResult=' . $this->_firstResult . '&maxResult=' . $this->_maxResults . '&hydrationMode='.$this->_hydrationMode.'DOCTRINE_QUERY_CACHE_SALT' ); }




[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-3497] orphanRemoval=true overrides onDelete="CASCADE" behaviour for One-To-Many Bidirectional associations (without Join Table) Created: 14/Jan/15  Updated: 14/Jan/15

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

Type: Improvement Priority: Minor
Reporter: Alex Prokop Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: cascade, mapping, ondelete, onetomany, orm, orphanRemoval
Environment:

PHP 5.5.11
MySQL 5.6.16 Source distribution


Attachments: File example.php    
Issue Links:
Reference
relates to DDC-3498 orphanRemoval=true for One-To-Many Bi... Open

 Description   

When removing entities from a collection, only the association is removed not the entity itself. But for One-To-Many Bidirectional associations without a Join Table, the database row on the Many-To-One side contains the information for both the association and the entity data. If when removing the association the desired behaviour is to delete the entity as well then orphanRemoval=true can be used on the One-To-Many annotation. However this overrides onDelete="CASCADE" if set on the JoinColumn of the Many-To-One side, resulting in unnecessary DELETE queries. Additionally, these queries are run separately for each entity in the collection, rather than as a single query as with Many-To-Many Join Tables (see linked issue). See example code attached.



 Comments   
Comment by Alex Prokop [ 14/Jan/15 ]

Both issues relate to One-To-Many associations without Join Tables, where the data row on the Many-To-One side is both association and entity data.





[DDC-3498] orphanRemoval=true for One-To-Many Bidirectional associations (without Join Table) produces unnecessary number of DELETE queries Created: 14/Jan/15  Updated: 14/Jan/15

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

Type: Improvement Priority: Minor
Reporter: Alex Prokop Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: mapping, onetomany, orm, orphanRemoval
Environment:

PHP 5.5.11
MySQL 5.6.16 Source distribution


Attachments: File example.php    
Issue Links:
Reference
is referenced by DDC-3497 orphanRemoval=true overrides onDelete... Open

 Description   

If orphanRemoval=true is set on a One-To-Many Bidirectional association without a Join Table, when removing the owning entity, multiple DELETE queries are generated. Since the row in the database on the Many-To-One side contains both the association and entity data, it should be possible to replace this with a single DELETE query using the owning entity's id, as when deleting associations in a Join Table for a Many-To-Many association. See attachment for example code.






[DDC-3491] Annotation for column value case sensitivity Created: 13/Jan/15  Updated: 13/Jan/15

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

Type: Improvement Priority: Minor
Reporter: Zoltán Halassy Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

It would be cool, if CHAR/VARCHAR case-sensitivity could be annotated on a column.

Every database driver would pick two default (config-overridable) collation, one for case-sensitive, and one for case-insensitive, and use those when the user requests or case-sensitive or insensitive column definition. This way the annotation would be portable.






[DDC-3367] [GH-1171] Improvements for complex select statements when using new object expression Created: 28/Oct/14  Updated: 13/Jan/15

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

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


 Description   

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

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

Message:

My update allows you to alias objects created with the ["new" object expression](http://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html#new-operator-syntax), as well as the ability to create queries that allow you to have multiple "new" object expressions and mixed scalar results.

Suppose you create a query as such:

```dql
SELECT new UserDTO(u.id,u.name) as user,new AddressDTO(a.street,a.postalCode) as address, a.id as addressId FROM User u INNER JOIN u.addresses a WITH a.isPrimary = true
```

upon executing this query, you'll end up with a result set that looks like the following:

```php
array(
0=>array(
0=>

{UserDTO object},
1=>{AddressDTO object},
2=>{u.id scalar},
3=>{u.name scalar},
4=>{a.street scalar},
5=>{a.postalCode scalar},
'addressId'=>{a.id scalar},
),
...
)
```

My changes fix that so you'd end up with a more usable result set:

```php
array(
0=>array(
'user'=>{UserDTO object}

,
'address'=>

{AddressDTO object}

,
'addressId'=>

{a.id scalar}

)
...
)
```



 Comments   
Comment by Doctrine Bot [ 13/Jan/15 ]

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





[DDC-3489] Sequence generators should be stateless Created: 13/Jan/15  Updated: 13/Jan/15

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

Type: Bug Priority: Major
Reporter: Marco Pivetta Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: metadata, sequence, sequence-generator, stateless

Issue Links:
Dependency
is required for DDC-2477 [GH-681] Sequence generator fix Resolved

 Description   

Current sequence generators keep internal state such as the metadata of the entity that uses the sequence.

The sequence generators should instead be stateless.






[DDC-3485] Using Embeddable in MappedSuperclass fails Created: 11/Jan/15  Updated: 11/Jan/15

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

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

Attachments: File EmbedInMappedSuperclass.php    

 Description   

While Trying to Embed an object into a mapped superclass an exception is thrown:

PHP Fatal error:  Uncaught exception 'Doctrine\ORM\Mapping\MappingException' with message 'Duplicate definition of column 'embed_someField' on entity 'Entity' in a field or discriminator column mapping.' in /home/dev/Workspace/symfony/perto/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/MappingException.php:555





[DDC-3476] JoinTable options are not inherited Created: 06/Jan/15  Updated: 06/Jan/15

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

Type: Bug Priority: Major
Reporter: Enrico Schultz Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: join, joins, orm, table-options


 Description   

I'm working with Symfony 2.6 and Doctrine (MySQL), but the error is in the Doctrine 2 ORM.

I have specified a ManyToMany relation like so:

/**
 *@ORM\Table(name="users", options={"engine"="MyISAM", "collate"="utf8_general_ci"})
 * @ORM\Entity
 */
class User
{
  /**
    * @ORM\ManyToMany(targetEntity="Group", inversedBy="users")
    * @ORM\JoinTable(name="user_groups", joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")}, inverseJoinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id")})
  */
  private $groups;

...
}

All tables should be created as MyISAM and "utf8_general_ci" collation instead of InnoDB and "utf8_unicode_ci". This works fine for all tables except for "user_groups" table because the options are not inherited. As a result the schema is not valid, because foreign keys cannot be created over 2 different collations.

To fix this, I modified class "\Doctrine\ORM\Tools\SchemaTool", function "gatherRelationsSql($class, $table, $schema, &$addedFks, &$blacklistedFks)" and added the following lines in the MANY_TO_MANY block:

if (isset($foreignClass->table['options'])) {
  foreach ($foreignClass->table['options'] as $key => $val) {
    $theJoinTable->addOption($key, $val);
  }
}

Now, it works as I want. The new table is created with the right collation and engine and the foreign keys are created correct. Could you please implement this fix?



 Comments   
Comment by Enrico Schultz