[DDC-2440] composer.json is wrong Created: 09/May/13  Updated: 09/May/13  Resolved: 09/May/13

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

Type: Bug Priority: Blocker
Reporter: Richard Nicol Assignee: Marco Pivetta
Resolution: Invalid Votes: 1
Labels: None


 Description   

In composer.json for doctrine/doctrine-orm-module there is the following require:
"doctrine/doctrine-module": "0.8.*"

However "0.8.*" does not exist, it should be "0.8.x-dev" or "dev-master". The later would then use the branch alias. Either way this needs changing, because it's stopping the package from being installed or updated.



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

Please open the ticket on the Doctrine ORM Module, this is the ORM bug tracker.

Comment by Richard Nicol [ 09/May/13 ]

Sorry my mistake! I have opened an issue on github here: https://github.com/doctrine/DoctrineORMModule/issues/219 in case anyone ends up here.

Cheers.

Comment by Marco Pivetta [ 09/May/13 ]

DoctrineModule has a 0.8.x branch. Closing





[DDC-1377] Doctrine doesn't understand associations from SINGLE_TABLE inheritances Created: 14/Sep/11  Updated: 15/Sep/11  Resolved: 15/Sep/11

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

Type: Bug Priority: Blocker
Reporter: Marcos Augusto da Silva Garcia Assignee: Guilherme Blanco
Resolution: Duplicate Votes: 0
Labels: None
Environment:

Xubuntu 11.04 Linux 2.6.38 i386


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

 Description   

Doctrine doesn't understand when a query is built from an association to a SINGLE_TABLE parent to get its successors relations.

For example:
Many Lice reside in an Animal (Louse @ManyToOne Animal)
Animals can specialize into Cats or Dogs (SINGLE_TABLE Inheritance)
A Dog can have one Bone (Dog @OneToOne Bone)
A Cat can have one Yarn (Yarn @OneToOne Yarn)

From a specific Louse, Doctrine can't get the Animal's Bone or Yarn.



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

Doctrine implements strict OO inheritance, what you want does not work as no casting is currently possible.

Comment by Guilherme Blanco [ 15/Sep/11 ]

Reopening

Comment by Guilherme Blanco [ 15/Sep/11 ]

Duplicate to DDC-16





[DDC-513] LEFT JOIN on extended entity of associated entity from parent by @OneToOne throw exception "no such column" [testcase included] Created: 12/Apr/10  Updated: 12/Apr/10  Resolved: 12/Apr/10

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

Type: Bug Priority: Blocker
Reporter: Ondrej Sibrina Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None

Attachments: File DDC513Test.php    

 Description   

Dear Roman ,

Watch testcase please to understand this issue.

Thank you.



 Comments   
Comment by Guilherme Blanco [ 12/Apr/10 ]

In http://github.com/doctrine/doctrine2/commit/56a8f5cd5353908b815607a6e089201c95e01e6c this issue was fixed.

Thanks for the report and unit test. It saved me a LOT of time!





[DDC-512] LEFT JOIN of extended null entity cause empty result [testcase included] Created: 12/Apr/10  Updated: 15/Apr/10  Resolved: 15/Apr/10

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

Type: Bug Priority: Blocker
Reporter: Ondrej Sibrina Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None

Attachments: File DDC512Test.php    

 Description   

Dear developers,

I'm not sure about propriety of my query but what i want to do is left
join entity which is associeted by @OneToOne. Problem occur when
associeted entity is NULL. Then i got empty result. I think it's
because my associeted entity is extended so it cause in final SQL
query inner joins which are not in subselect.

class Shop_Data_Entity_StockItem extends Shop_Data_Entity_Item

{ /** * @OneToOne(targetEntity="Shop_Data_Entity_OrderItem", mappedBy="stockItem") */ protected $orderItem; ... }

So there's my query:

$q = $em->createQuery("select u from Shop_Data_Entity_StockItem u left
join u.orderItem uu");
echo $q->getSql();
$result = $q->getResult();
count($result[0]);

// print 0 even there're Shop_Data_Entity_StockItem in database and
without left join clause prints 2

There's echo $q->getSql():

SELECT s0_.ean AS ean0, s0_.title AS title1, s0_.description AS
description2, s0_.vat AS vat3, s0_.id AS id4, s1_.bestBefore AS
bestBefore5, s0_.discr AS discr6, s0_.price AS price7,
s1_.deliveryInvoice_id AS deliveryInvoice_id8 FROM
Shop_Data_Entity_StockItem s1_ INNER JOIN Shop_Data_Entity_Item s0_ ON
s1_.id = s0_.id LEFT JOIN Shop_Data_Entity_OrderItem s2_ ON s1_.id =
s2_.stockItem_id INNER JOIN Shop_Data_Entity_OfferItem s3_ ON s2_.id =
s3_.id INNER JOIN Shop_Data_Entity_Item s4_ ON s2_.id = s4_.id



 Comments   
Comment by Ondrej Sibrina [ 12/Apr/10 ]

This test case is slightly different from example i wrote in description but shows same issue

Comment by Guilherme Blanco [ 12/Apr/10 ]

Your report exposes exactly the issue pointed on DDC-349.

We should take a look how to fix this without having to update ALL unit tests that takes advantage of inheritance.

Also, the SQL spec requires that all joins need to be specified before write the ON keyword.
Example:

Exception: [PDOException] SQLSTATE[HY000]: General error: 1 a JOIN clause is required before ON
SELECT d0_.id AS id0, d0_.item AS item1 FROM DDC512Customer d0_ LEFT JOIN (DDC512OfferItem d1_ ON d0_.item = d1_.id INNER JOIN DDC512Item d2_ ON d1_.id = d2_.id)

And in the situation of a inheritance:

Exception: [PDOException] SQLSTATE[HY000]: General error: 1 a JOIN clause is required before ON             
SELECT o0_.id AS id0, o0_.name AS name1, o3_.id AS id2, o3_.name AS name3, o0_.discr AS discr4, o0_.mother_id AS mother_id5, o3_.discr AS discr6, o3_.mother_id AS mother_id7 FROM OJTIC_Pet o0_ LEFT JOIN OJTIC_Cat o1_ ON o0_.id = o1_.id LEFT JOIN OJTIC_Dog o2_ ON o0_.id = o2_.id INNER JOIN (OJTIC_Pet o3_ ON o0_.id = o3_.mother_id LEFT JOIN OJTIC_Cat o4_ ON o3_.id = o4_.id LEFT JOIN OJTIC_Dog o5_ ON o3_.id = o5_.id) WHERE o0_.name = 'Poofy' ORDER BY o3_.name ASC
Comment by Roman S. Borschel [ 13/Apr/10 ]

I am aware of the problem and yes, nested joins for CTI can be a solution but its just 1 solution. The other one is to simply turn these CTI joins into left joins when they appear in the middle of a query (that is, not in the FROM clause).

So, given a Class hierarchy like this:

class Item
class StockItem extends Item
class OfferItem extends Item
class OrderItem extends OfferItem

StockItem <-onetoone-> OrderItem

and a DQL like this:

DQL: select s from StockItem s left join s.orderItem o ...

We have 2 possible solutions.

Nr. 1: Nested inner join

SELECT ... FROM stockitem s1_
INNER JOIN item s0_ ON s1_.id = s0_.id
LEFT JOIN
    (orderitem s2_ INNER JOIN offeritem s3_ ON s2_.id = s3_.id
     INNER JOIN item s4_ ON s2_.id = s4_.id)
ON s1_.id = s2_.stockItem_id

Nr. 2: Just use left joins for parent tables for all CTI joins that are the result of a DQL join (This is what Hibernate does):

SELECT ... FROM stockitem s1_
INNER JOIN item s0_ ON s1_.id = s0_.id
LEFT JOIN orderitem s2_ ON s1_.id = s2_.stockItem_id
LEFT JOIN offeritem s3_ ON s2_.id = s3_.id
LEFT JOIN item s4_ ON s2_.id = s4_.id

According to DDC-349, most databases seem to support nested inner joins (Nr. 1) but nevertheless its not in the ANSI standard I think, so I am not sure we can rely on it.

The Hibernate solution seems simpler but I still wonder whether they perform differently (Usually, inner joins are more performant than outer joins),

Comment by Roman S. Borschel [ 15/Apr/10 ]

Fixed in http://github.com/doctrine/doctrine2/commit/01c2c06bbf529d89c9741ea97702359509ea230a using the "hibernate-way".

Please note that you currently should not name join columns the same as entity fields. See DDC-522. Better use @JoinColumn(name="item_id", ...)





[DDC-422] Unable to add entity in @ManyToMany association when owning entity is extended from another entity Created: 14/Mar/10  Updated: 18/Mar/10  Resolved: 18/Mar/10

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA4
Fix Version/s: 2.0-BETA1
Security Level: All

Type: Bug Priority: Blocker
Reporter: Ondrej Sibrina Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None
Environment:

PHP 5.3.2


Attachments: File DDC406Test.php    

 Description   

Dear developers,

I'm not sure if i extend entities in right way but i found different behaviour in extended entity which won't process add in @ManyToMany association.
My class are defined like this:

/**
 * @Entity
 * @HasLifecycleCallbacks
 * @InheritanceType("JOINED")
 * @DiscriminatorColumn(name="discr", type="string")
 * @DiscriminatorMap({"guest" = "Shop_Data_Entity_Guest", "customer" = "Shop_Data_Entity_Customer"})
 */
class Shop_Data_Entity_Guest extends Shop_Data_Entity_Abstract {
    public function __construct() {
        /* call parent construct with all parameters */
        call_user_func_array(array("parent","__construct"),func_get_args());
    }
}

/**
 * @Entity
 * @HasLifecycleCallbacks
 */
class Shop_Data_Entity_Customer extends Shop_Data_Entity_Guest {
    /**
     * @ManyToMany(targetEntity="Shop_Data_Entity_Contact", cascade={"persist","remove"} )
     * @JoinTable(name="Shop_Data_Entity_Customer__homes",
     *      joinColumns={@JoinColumn(name="customer_id", referencedColumnName="id", onDelete="cascade" )},
     *      inverseJoinColumns={@JoinColumn(name="contact_id", referencedColumnName="id", onDelete="cascade" )}
     *      )
     */
    public $homes;

    public function __construct() {
        /* call parent construct with all parameters */
        call_user_func_array(array("parent","__construct"),func_get_args());

        $this->homes = new Shop_Data_Collection_Standard(); // this class only extends ArrayCollection
    }
}

When i fire this code:

        $q = $em->createQuery("select c from Shop_Data_Entity_Customer c");
        $q->setMaxResults(1);
        $customers = $q->getResult();
        
        $contact = new Shop_Data_Entity_Contact();
        $customers[0]->home->add($contact);
        $em->flush();

There's no change in database.
When i change definition od Guest class like this:

/** @MappedSuperclass */
class Shop_Data_Entity_Guest extends Shop_Data_Entity_Abstract {
    public function __construct() {
        /* call parent construct with all parameters */
        call_user_func_array(array("parent","__construct"),func_get_args());
    }
}

It start work and every firing of my code add one contact and association to my database. It causes problem only when owning entity is quered from database at first.



 Comments   
Comment by Ondrej Sibrina [ 16/Mar/10 ]

I tried to debug by myself and i found that on line 411 in UnitOfWork.php is on flush in first example $class->associationMappings == null. When i change Shop_Data_Entity_Guest to /** @MappedSuperclass */ i can find $class->associationMappings on same line with some elements.

Hope it help to fix it

Andy

Comment by Ondrej Sibrina [ 16/Mar/10 ]

I tried to made patch by myself and it looks it start working. I'm not sure if this solution is proper. Andy

from line 1731 of UnitOfWork.php

 if (isset($this->_identityMap[$class->name][$idHash])) {  // $$class->rootEntityName to $class->name
            $entity = $this->_identityMap[$class->name][$idHash]; // $class->rootEntityName to $class->name
            $oid = spl_object_hash($entity);
            if ($entity instanceof Proxy && ! $entity->__isInitialized__) {
                $entity->__isInitialized__ = true;
                $overrideLocalValues = true;
            } else {
                $overrideLocalValues = isset($hints[Query::HINT_REFRESH]);
            }
        } else {
            //$entity = clone $class->prototype;
            $entity = new $className;
            $oid = spl_object_hash($entity);
            $this->_entityIdentifiers[$oid] = $id;
            $this->_entityStates[$oid] = self::STATE_MANAGED;
            $this->_originalEntityData[$oid] = $data;
            $this->_identityMap[$class->name][$idHash] = $entity; // $class->rootEntityName to $class->name
Comment by Ondrej Sibrina [ 16/Mar/10 ]

To ensure i checkouted trunk version but it doesn't solve this problem.

Andy

Comment by Ondrej Sibrina [ 16/Mar/10 ]

After using my patch i can't do $em->remove properly any other patch?

Comment by Roman S. Borschel [ 18/Mar/10 ]

This is fixed now in trunk.

Comment by Ondrej Sibrina [ 18/Mar/10 ]

Thank you very much Hope this report was better than my first one.





[DDC-50] Call to undefined method Doctrine\ORM\Mapping\OneToManyMapping::getQuotedJoinColumnName() Created: 15/Oct/09  Updated: 15/Oct/09  Resolved: 15/Oct/09

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA3
Fix Version/s: 2.0-ALPHA3
Security Level: All

Type: Bug Priority: Blocker
Reporter: Arthur Purnama Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None
Environment:

PHP 5.3.0 (cli) (built: Jul 21 2009 08:22:07)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies

Server Version: Apache/2.2.11 (Ubuntu) mod_jk/1.2.26 PHP/5.2.6-3ubuntu4.2 with Suhosin-Patch
Server Built: Aug 18 2009 14:26:31

mysql Ver 14.14 Distrib 5.1.31, for debian-linux-gnu (i486) using EditLine wrapper


Attachments: File kateglox.sql     Zip Archive kateglo_doctrine.zip    

 Description   

with the $config->setAllowPartialObjects(false); i make an query to
phrase, and get a phrase object. sofar so good

but as i try to get the type or lexical member like $phrase->getType()
it throws a Fatal error like this:

Fatal error: Call to undefined method
Doctrine\ORM\Mapping\OneToManyMapping::getQuotedJoinColumnName() in
/usr/local/zend/apache2/htdocs/doctrine/lib/Doctrine/ORM/Persisters/StandardEntityPersister.php
on line 599

i read this on doctrine-user groups

http://groups.google.com/group/doctrine-user/browse_thread/thread/a15d430b4ae483b4/dc7665ed137a4e78?lnk=gst&q=getQuotedJoinColumnName#dc7665ed137a4e78

and i take a look if the line

$owningAssoc = $this->_class->associationMappings[$coll->getMapping()->mappedByFieldName];

present on StandardEntityPersister#loadOneToManyCollection.

and yes. its present. but i still got this error.



 Comments   
Comment by Roman S. Borschel [ 15/Oct/09 ]

Should be fixed now in HEAD.





[DDC-51] Notice: Undefined index: [columnName] in/Doctrine/ORM/Mapping/OneToManyMapping.php on line 129 Created: 15/Oct/09  Updated: 15/Oct/09  Resolved: 15/Oct/09

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA3
Fix Version/s: 2.0-ALPHA3
Security Level: All

Type: Bug Priority: Blocker
Reporter: Arthur Purnama Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None
Environment:

« Hide
PHP 5.3.0 (cli) (built: Jul 21 2009 08:22:07)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies

Server Version: Apache/2.2.11 (Ubuntu) mod_jk/1.2.26 PHP/5.2.6-3ubuntu4.2 with Suhosin-Patch
Server Built: Aug 18 2009 14:26:31

mysql Ver 14.14 Distrib 5.1.31, for debian-linux-gnu (i486) using EditLine wrapper



 Description   

With the same example as DDC-50

i now can not get the ManyToOne association (definitions, proverbs and relations);

i got php notice
Notice: Undefined index: phrase_id in /usr/local/zend/apache2/htdocs/doctrine/lib/Doctrine/ORM/Mapping/OneToManyMapping.php on line 129

if i check the line the variable $joinColumnValues is an empty array, because the PersistentCollection.php at line 233 did not send any joincolumnvalues to the load method. i dont know if this the cause.

i have try to set $entityManager->getConfiguration()->setAllowPartialObjects() to TRUE and make an dql like this
"SELECT p, d FROM ".models\Phrase::CLASS_NAME." p join p.definitions d WHERE p.phrase = '$phrase'"

but the result is still the same



 Comments   
Comment by Roman S. Borschel [ 15/Oct/09 ]

Can you please show the code that you're using. I dont mean the models but the code that causes this problem.

Thanks.

Comment by Arthur Purnama [ 15/Oct/09 ]

$definitions = $phrase->getDefinitions();
var_dump($definitions[0] instanceof kateglo\application\models\Definition);

hope this help you.

regards,
arthur

Comment by Roman S. Borschel [ 15/Oct/09 ]

Okay, thanks, I can reproduce this and will work on this. When I'm done I will add all these new tests to the test suite.

Comment by Roman S. Borschel [ 15/Oct/09 ]

By the way, eager loading works fine for me. See this snippet:


        $query = $this->_em->createQuery("SELECT p,d FROM Doctrine\Tests\ORM\Functional\Phrase p JOIN p.definitions d");
        $res = $query->getResult();
        $definitions = $res[0]->getDefinitions();
        
        $this->assertEquals(1, count($res));
        $this->assertTrue($definitions[0] instanceof Definition);

This works for me. But lazy-loading results in the error you mentioned and which I will fix.

Comment by Arthur Purnama [ 15/Oct/09 ]

ok thank you very much it works like charm.

du bist Gold Wert Roman

please close the ticket.

Regards,
Arthur





[DDC-49] Incomplete MySQL Query Generator (MySQL Syntax error) Created: 15/Oct/09  Updated: 15/Oct/09  Resolved: 15/Oct/09

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

Type: Bug Priority: Blocker
Reporter: Arthur Purnama Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None
Environment:

PHP 5.3.0 (cli) (built: Jul 21 2009 08:22:07)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies

Server Version: Apache/2.2.11 (Ubuntu) mod_jk/1.2.26 PHP/5.2.6-3ubuntu4.2 with
Suhosin-Patch
Server Built: Aug 18 2009 14:26:31

mysql Ver 14.14 Distrib 5.1.31, for debian-linux-gnu (i486) using EditLine wrapper


Attachments: Zip Archive kateglo_doctrine.zip     File Lexical.php     File PhraseType.php    

 Description   

i checkout the HEAD version. and try to write this DQL

$query = utilities\DataAccess::getEntityManager()->createQuery("SELECT
p, t FROM ".models\Phrase::CLASS_NAME." p join p.type t WHERE p.phrase
= '$phrase'");

i commented out the $config->setAllowPartialObjects(false);

and have PDO error that my MySQL statement sytax is invalid.

i check the Query that the Doctrine create and its like this :
SELECT p0_.phrase_id AS phrase_id0, p0_.phrase_name AS phrase_name1,
p1_.phrase_type_id AS phrase_type_id2, p1_.phrase_type_name AS
phrase_type_name3, p1_.phrase_type_abbreviation AS
phrase_type_abbreviation4 FROM phrase p0_ INNER JOIN phrase_type p1_
ON p0_.phrase_type_id = p1_. WHERE p0_.phrase_name = 'abu'

as you can si at the ON statement it writes p0_.phrase_type_id = p1_.

the p1_. is not completed. i think my DocAnnotation is OK, because i
look at the Doctrine Tests Models that test the OneToMany Function
(the one with the ECommerce models, product and features). I have
followed all the doc annotation writes there.



 Comments   
Comment by Roman S. Borschel [ 15/Oct/09 ]

Should be fixed now in HEAD.





[DDC-24] text type not portable (works only on MySQL) Created: 30/Sep/09  Updated: 14/Jun/10  Resolved: 01/Oct/09

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA2
Fix Version/s: 2.0-ALPHA2
Security Level: All

Type: Bug Priority: Blocker
Reporter: Ismo Toijala Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None


 Description   

The text type is not portable to other RDBMS than MySQL. To support the text type, a platform must implement the method getClobDeclarationSql(array $field). Currently only MySqlPlatform has this method. This means that attempting to use the CLI tool to create a schema with a text column using another RDBMS fails with the following error:

Fatal error: Call to undefined method Doctrine\DBAL\Platforms\SqlitePlatform::getClobDeclarationSql() in D:\Projects\Test\tools\sandbox\lib\Doctrine\DBAL\Types\TextType.php on line 15

I believe at least Sqlite supports the CLOB type.

Either the text type should be supported by all platforms or the documentation should be revised. Currently it says:

"All Doctrine Mapping Types that ship with Doctrine are fully portable between different RDBMS."

This makes easy testing of models using sqlite with minimum configuration impossible with the text type.



 Comments   
Comment by Roman S. Borschel [ 30/Sep/09 ]

Thanks. We will try to address this as soon as possible. This is just an oversight in the implementation. The text type can definitely be made portable across all platforms.





[DDC-2845] booking Created: 08/Dec/13  Updated: 08/Dec/13  Resolved: 08/Dec/13

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

Type: New Feature Priority: Critical
Reporter: wishver Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: None
Environment:

Environment test



 Description   

DescriptiontestDescriptiontest
Descriptiontest
Descriptiontest
Descriptiontest






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

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

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

Ubuntu 12.10, Zend Server CE



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

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

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

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



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

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





[DDC-2179] Transactions should sent in group not chunked Created: 29/Nov/12  Updated: 30/Nov/12  Resolved: 30/Nov/12

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

Type: Bug Priority: Critical
Reporter: Florin Patan Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: unitofwork
Environment:

MySQL 5.5 / Percona



 Description   

In UnitOfWork::commit() it seems that a transaction is done like this:

  • will send separate queries for transaction start
  • compute the queries/send them to the db driver
  • execute the commit statement
  • optionally execute rollback

The question would be, should my webserver have some issues with resources, wouldn't this part of the code be a pain for the DB?

I don't know how mysql, for example, handles sending the transaction in chunks as opposed to sending it in 2/3 statements ( begin + ops and commit / + revert in case of failure) or in mySQL,l the transaction is evaluated on COMMIT statement only?

If my assumption about how MySQL works, locking everything as soon as the statement is on the server, then shouldn't Doctrine use a internal buffer for sending transactions to the DB driver in order to avoid all sorts of problems that appear in high concurency scenarios?

Best regards.



 Comments   
Comment by Marco Pivetta [ 30/Nov/12 ]

Invalid IMO. This is an over-complication that (in such high load scenarios) is handled by clustering/load balancing. Not a problem of the ORM, since smashing all statements together will just make it impossible to trap any problems.

Comment by Marco Pivetta [ 30/Nov/12 ]

This performance improvement has been discussed directly on IRC.

The original problem is related to deadlocks and small transactions, which is not anyway solved by this issue.

Otherwise, this improvement requires a PoC that shows that it is possible to have exceptions still showing the query that caused the failure.

Comment by Marco Pivetta [ 30/Nov/12 ]

Sorry, was unclear. I basically mean that any approach squashing the queries into a single chunk sent to the DB should also allow us to get computed insert IDs and eventual exceptions should bubble up with the query that caused them.





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

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

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

Ubuntu 12.04, PHP 5.3, 64 Bit, Symfony 2


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

 Description   

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

/**
*

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

    )
    */
    protected $data;

Will cause an error when deleting the objects:

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

{"1":19306}

:

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

Removing indexBy fixes the issue.

My class structure is:

Location has many LocationData
LocationData extends AbstractData

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



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

Hi James

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

Thanks

Comment by James Bench [ 28/Sep/12 ]

Entity exhibiting the behavior.

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

Hi James,
I can't reproduce,

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

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

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

Thanks

Comment by James Bench [ 02/Oct/12 ]

Hi Fabio,

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

How would I run the test against a MySQL db?

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

Cheers,JB

Comment by James Bench [ 02/Oct/12 ]

SQL Log from script causing errors.

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

Hi James,

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

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

Comment by James Bench [ 02/Oct/12 ]

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

Comment by James Bench [ 02/Oct/12 ]

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

Not sure whether you would consider this a bug.

Thanks for your help.

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

No problem, you are welcome

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

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

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

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

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

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





[DDC-1352] ErrorException: Undefined index in array Created: 30/Aug/11  Updated: 01/Sep/11  Resolved: 01/Sep/11

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

Type: Bug Priority: Critical
Reporter: Søren Assignee: Guilherme Blanco
Resolution: Invalid Votes: 0
Labels: None
Environment:

Windows 7, PHP 5.3.3



 Description   

The following query:
"select c.id
from \\Domain
Cuisine c
left join c.nameTranslation t
left join t.translationValues v
left join v.language l
where v.value = :name
and l.id = :languageId"

Results in a PHP ErrorException in \Doctrine\ORM\Query\SqlWalker line 745:
$assoc = ( ! $relation['isOwningSide']) ? $targetClass->associationMappings[$relation['mappedBy']] : $relation;

When I step through the execution, the array entry: $relation['mappedBy'] gets the following value: "Domain\Translation" in the scope where the error occurs.
$targetClass->associationMappings has the following indices: "translation" and "language" and this leads to a "Undefined index" error and the execution breaks. It means that I cannot execute DQL queries, which is critical for the application to run.

<entity name="Domain\Cuisine" table="Cuisine" repository-class="Infrastructure\Persistence\Doctrine\Repository\CuisineRepository">
<id name="id" type="integer" column="Id">
<generator strategy="AUTO"/>
</id>
<many-to-one target-entity="Domain\Translation" field="nameTranslation">
<join-column name="NameTranslation_Id" referenced-column-name="Id"/>
</many-to-one>
</entity>

<entity name="Domain\Translation" table="Translations">
<id name="id" type="integer" column="Id">
<generator strategy="AUTO" />
</id>
<one-to-many target-entity="Domain\TranslationValue" mapped-by="Domain\Translation" field="translationValues" orphan-removal="true">
<cascade>
<cascade-all/>
</cascade>
</one-to-many>
</entity>

<entity name="Domain\TranslationValue" table="TranslationValues">
<id name="id" type="integer" column="Id">
<generator strategy="AUTO" />
</id>

<field name="value" type="string" column="Value" />

<many-to-one field="translation" target-entity="Domain\Translation">
<join-column name="Translation_Id" nullable="false" referenced-column-name="Id" />
</many-to-one>

<many-to-one field="language" target-entity="Domain\Language">
<join-column name="Language_Id" nullable="false" referenced-column-name="Id" />
</many-to-one>
</entity>

<entity name="Domain\Language" table="Languages" repository-class="\Infrastructure\Persistence\Doctrine\Repository\TranslationRepository">
<id name="id" type="integer" column="Id">
<generator strategy="AUTO" />
</id>
<field name="name" type="string" column="Name" />
<field name="shortIsoCode" type="string" column="ShortIsoCode"/>
<field name="longIsoCode" type="string" column="LongIsoCode"/>
<field name="isDefault" type="boolean" column="IsDefault" />
</entity>



 Comments   
Comment by Guilherme Blanco [ 01/Sep/11 ]

Your mapping information is wrong.
The mappedBy value must reference the field name of the owning side, and not the class name.

Marking ticket as invalid.





[DDC-802] Missing variable $name in XmlExporter Created: 14/Sep/10  Updated: 15/Sep/10  Resolved: 15/Sep/10

Status: Closed
Project: Doctrine 2 - ORM
Component/s: Tools
Affects Version/s: 2.0-BETA4
Fix Version/s: 2.0-RC1
Security Level: All

Type: Bug Priority: Critical
Reporter: Martin Hasoň Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None


 Description   

At line 112 http://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Tools/Export/Driver/XmlExporter.php#L112 is required variable $name. This variable should be replaced by $unique['name']. And before this line should be test if(isset($unique['name'])).



 Comments   
Comment by Guilherme Blanco [ 15/Sep/10 ]

On http://github.com/doctrine/doctrine2/commit/4845745337dbbed5eead25c3062a07103b38649f I fixed this issue.

Thanks for the report.





[DDC-610] Numeric strings are not quoted Created: 25/May/10  Updated: 25/May/10  Resolved: 25/May/10

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-BETA1
Fix Version/s: 2.0-BETA2
Security Level: All

Type: Bug Priority: Critical
Reporter: David Abdemoulaie Assignee: David Abdemoulaie
Resolution: Fixed Votes: 0
Labels: None


 Description   

I've been working on a MaterializedPath implementation and hit a roadblock.

This condition:

// $pathInterval = array('00010001', '0001ZZZZ');
$andX->add($expr->between('e.' . $this->getPathFieldName(), $expr->literal($pathInterval[0]), $expr->literal($pathInterval[1])));

results in this SQL:

AND (l0_.path BETWEEN 00010000 AND '0001ZZZZ')

This is clearly not correct. Numeric strings should still be quoted if the field is of type string.



 Comments   
Comment by David Abdemoulaie [ 25/May/10 ]

Fixed in http://github.com/doctrine/doctrine2/commit/b6a5402bcb014e78eb6c0b841609e6f0bba71ef6





[DDC-604] array_merge in Query::_doExecute causes parameter reordering Created: 20/May/10  Updated: 07/Jun/10  Resolved: 07/Jun/10

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-BETA1
Fix Version/s: 2.0-BETA2
Security Level: All

Type: Bug Priority: Critical
Reporter: David Abdemoulaie Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None


 Description   

Hi all,
I think there is a bug with the doExecute method from the Query class.

foreach ($this->_params as $key => $value) { 
            if ( ! isset($paramMappings[$key])) { 
                throw QueryException::unknownParameter($key); 
            } 
            if (isset($this->_paramTypes[$key])) { 
                foreach ($paramMappings[$key] as $position) { 
                    $types[$position] = $this->_paramTypes[$key]; 
                } 
            } 
            if (is_object($value) && 
$this->_em->getMetadataFactory()->hasMetadataFor(get_class($value))) { 
                $values = 
$this->_em->getUnitOfWork()->getEntityIdentifier($value); 
                $sqlPositions = $paramMappings[$key]; 
                $sqlParams = array_merge($sqlParams, 
array_combine((array)$sqlPositions, $values)); 
            } else { 
                foreach ($paramMappings[$key] as $position) { 
                    $sqlParams[$position] = $value; 
                } 
            } 
        } 

When constructing the $sqlParams array, array_merge is used for params wich
are objects. Php documentation says that numeric key are renumbered. So we
loose the position of the parameter.
I solved this problem by replacing the array_merge with that :
$sqlParams = $sqlParams + array_combine((array)$sqlPositions, $values);
But I'm not sure it doesn't have unwanted effects.
I created a fork on github for this bug, hope it could be usefull.

Edit a fail case :

SQL (for postgres):

CREATE TABLE first_class
(
  id serial NOT NULL,
  "text" character varying,
  second_class_id integer,
  CONSTRAINT first_class_pkey PRIMARY KEY (id),
  CONSTRAINT first_class_second_class_id_fkey FOREIGN KEY (second_class_id)
      REFERENCES second_class (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
);

CREATE TABLE second_class
(
  id serial NOT NULL,
  CONSTRAINT second_class_pkey PRIMARY KEY (id)
);

INSERT INTO second_class(
            id)
    VALUES (1);

FirstClass.php

/**
 * @Entity
 * @Table(name="first_class")
 */
class FirstClass {
  /**
   * @Id
   * @Column(name="id",type="integer")
   */
  private $id;
  /** @Column(name="text",type="string") */
  private $text;
  /**
   * @OneToOne(targetEntity="SecondClass")
   * @JoinColumn(name="second_class_id", referencedColumnName="id")
   */
  private $secondClassInstance;
}

SecondClass.php

/**
 * @Entity
 * @Table(name="second_class")
 */
class SecondClass {
  /**
   * @Id
   * @Column(name="id",type="integer")
   */
  private $id;
}

Test Case :

$secondClassInstance = $doctrineEntityManager->find('SecondClass',1);

$query = $doctrineEntityManager->createQuery("SELECT f FROM FirstClass f WHERE f.text = :text AND f.secondClassInstance = :instance")->setParameters(array('instance'=>$secondClassInstance,'text'=>'Un texte en francais',));
echo $query->getSQL();
$query->execute();

When you execute this query it fails. When printing the $sqlParams variable from _doExecute you can see the folowing :
Array ( [0] => 1 [1] => Un texte en francais )



 Comments   
Comment by David Abdemoulaie [ 20/May/10 ]

Brought Paul's changes over to doctrine/orm in branch DDC-604 http://github.com/doctrine/orm/tree/DDC-604

Comment by Paul Fariello [ 22/May/10 ]

I've just added the fail case





[DDC-599] Inheritance breaks cascading Created: 18/May/10  Updated: 07/Jun/10  Resolved: 07/Jun/10

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

Type: Bug Priority: Critical
Reporter: Nico Kaiser Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None

Attachments: File DDC599Test.php    

 Description   

When using inheritance, cascade=

{"delete"} does not work anymore:

This example creates three Entities:
- Item
- SubItem (extends Item)
- Child

The Item has a OneToMany association with Child with cascade={"delete"}

, so if an Item is deleted, its Children are deleted too.

http://pastie.org/965096

However this does not work, the cascade is ignored when the Item is deleted. Without inheritance (e.g. only Item with Children) it works perfectly.



 Comments   
Comment by Nico Kaiser [ 18/May/10 ]

By the way, this cannot be reproduced with the included testcases (no DB connection). So the problem may be between the ORM and the DBAL...

Comment by Roman S. Borschel [ 18/May/10 ]

Do you get any error message? exception? stack trace?

Comment by Nico Kaiser [ 18/May/10 ]

PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`kaiser_sandbox`.`Child`, CONSTRAINT `Child_ibfk_1` FOREIGN KEY (`parentId`) REFERENCES `Item` (`id`))' in /home/kaiser/doctrine/doctrine/lib/Doctrine/DBAL/Connection.php:637
Stack trace:
#0 /home/kaiser/doctrine/doctrine/lib/Doctrine/DBAL/Connection.php(637): PDOStatement->execute(Array)
#1 /home/kaiser/doctrine/doctrine/lib/Doctrine/DBAL/Connection.php(385): Doctrine\DBAL\Connection->executeUpdate('DELETE FROM Ite...', Array)
#2 /home/kaiser/doctrine/doctrine/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php(353): Doctrine\DBAL\Connection->delete('Item', Array)
#3 /home/kaiser/doctrine/doctrine/lib/Doctrine/ORM/UnitOfWork.php(777): Doctrine\ORM\Persisters\BasicEntityPersister->delete(Object(Entities\SubItem))
#4 /home/kaiser/doctrine/doctrine/lib/Doctrine/ORM/UnitOfWork.php(316): Doctrine\ORM\UnitOfWork->_executeDeletions(Object(Doctri in /home/kaiser/doctrine/doctrine/lib/Doctrine/DBAL/Connection.php on line 637

Comment by Roman S. Borschel [ 19/May/10 ]

Scheduled for beta2 but not sure we can make it, might end up on beta3. Increasing priority though as this seems to be a bug and these have priority.

Comment by Benjamin Eberlei [ 06/Jun/10 ]

Attached a test-case that verifies this bug exists.

Problem is the CommitOrderNodeCalculator not knowing about sub-class dependencies.





[DDC-593] Subquery parenthesis omitted in generated SQL Created: 16/May/10  Updated: 16/May/10  Resolved: 16/May/10

Status: Closed
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: 2.0-BETA1
Fix Version/s: 2.0-BETA2
Security Level: All

Type: Bug Priority: Critical
Reporter: John Kleijn Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None


 Description   

$dQuery = $this->_em->createQuery(
'SELECT p FROM entity\system\Group p WHERE (p.lft >= (SELECT t.lft FROM entity\system\Group t WHERE t.name = :name)) AND (p.rgt <= (SELECT t2.rgt FROM entity\system\Group t2 WHERE t2.name = :name))');

As you see this includes brackets around the subqueries.

var_dump($dQuery->getSQL());

SELECT s0_.level AS level0, s0_.lft AS lft1, s0_.rgt AS rgt2, s0_.id AS id3, s0_.name AS name4, s0_.description AS description5 FROM system_group s0_ WHERE (s0_.lft >= SELECT s1_.lft FROM system_group s1_ WHERE s1_.name = ?) AND (s0_.rgt <= SELECT s2_.rgt FROM system_group s2_ WHERE s2_.name = ?)

Brackets gone, resulting in:

'PDOException' with message '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 'SELECT s1_.lft FROM system_group s1_ WHERE s1_.name = 'root') AND (s0_.rgt <= SE' at line 1' in /usr/share/php/lib/Doctrine/DBAL/Connection.php:566

Brackets added and executed against database

SELECT s0_.level AS level0, s0_.lft AS lft1, s0_.rgt AS rgt2, s0_.id AS id3, s0_.name AS name4, s0_.description AS description5 FROM system_group s0_ WHERE (s0_.lft >= (SELECT s1_.lft FROM system_group s1_ WHERE s1_.name = "root")) AND (s0_.rgt <= (SELECT s2_.rgt FROM system_group s2_ WHERE s2_.name = "root"))

Works (MySQL).



 Comments   
Comment by John Kleijn [ 16/May/10 ]

Double brackets in the DQL results in

"exception 'Doctrine\ORM\Query\QueryException' with message '[Syntax Error] line 0, col 62: Error: Expected Literal, got 'SELECT'' in /usr/share/php/lib/Doctrine/ORM/Query/QueryException.php:42

Comment by Roman S. Borschel [ 16/May/10 ]

This might be caused by recent AST optimizations and thus I suspect this to be a regression.

Comment by John Kleijn [ 16/May/10 ]

Is there a workaround (other than not using a subquery)?

Comment by Roman S. Borschel [ 16/May/10 ]

Well, a workaround for any DQL issues that is always available is a NativeQuery (createNativeQuery). In essence, a DQL query is just a high-level abstraction for a native SQL query + a ResultSetMapping. http://www.doctrine-project.org/projects/orm/2.0/docs/reference/native-sql/en#native-sql

The resulting objects from a native query are still fully managed and all, so its just a difference in query abstraction.

Nevertheless, this should be fixed soon.

Comment by Roman S. Borschel [ 16/May/10 ]

Reproduced this successfully and already have a potential fix. Might not be a regression after all but a bug nevertheless.

Comment by Roman S. Borschel [ 16/May/10 ]

Should be fixed now in HEAD (doctrine2/master).





[DDC-518] Merging an entity with a one to one association to a MANAGED entity with no id throws 'The given entity has no identity.' Created: 13/Apr/10  Updated: 30/Jul/10  Resolved: 30/Jul/10

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

Type: Bug Priority: Critical
Reporter: Dave Keen Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None

Attachments: Text File ddc518.patch    

 Description   

Calling merge($entity) where $entity has a one to one association to another entity that has been persisted but not yet flushed (when using auto-generated ids) throws 'The given entity has no identity.'

It looks like it does this because _doMerge in UnitOfWork assumes for one to one associations only that the associated entity has an id and calls registerManaged, which then calls addToIdentityMap)on it.

I think that registeredManaged should only be called if !isset($this->_entityInsertions[spl_object_hash($other)])

Reproduce.php
// This is a new element
$doctor = new \vo\Doctor(); $d1->name = "New doctor";

// This is a detached element which is in the database
$patient = new \vo\Patient(); $p1->name = "Existing patient"; $p1->id = 1;

$doctor->patients->add($patient);
$patient ->doctor = $doctor;

$em->persist($doctor);

// This throws InvalidArgumentException: The given entity has no identity. in D:\Projects\ORM\flextrine2\flextrine\web\lib\Doctrine\ORM\UnitOfWork.php on line 1014
$em->merge($patient);
Doctor.php
class Doctor {

    /** @Id @Column(type="integer") @GeneratedValue(strategy="IDENTITY") */
    public $id;
	
    /** @Column(length=100, type="string") */
    public $name;
	
	/**
     * @OneToMany(targetEntity="Patient", mappedBy="doctor", fetch="EAGER")
     */
	public $patients;
	
	public function __construct() {
		$this->patients = new ArrayCollection();
	}
	
}
Patient.php
class Patient {
	
	var $_explicitType = "vo/Patient";
	
    /** @Id @Column(type="integer") @GeneratedValue(strategy="IDENTITY") */
    public $id;
	
    /** @Column(length=100, type="string") */
    public $name;

	/**
     * @OneToOne(targetEntity="Doctor", inversedBy="patients")
	 * @JoinColumn(name="doctor_id", referencedColumnName="id")
     */
	public $doctor;
	
}


 Comments   
Comment by Roman S. Borschel [ 08/May/10 ]

I think the order of operations in your example is not correct even though the error is misleading.

You are associating a "new doctor" to a "detached patient". That does not seem right, remember that merge() returns a managed copy, thus when merging the patient later, the "new doctor" is still associated with the "detached patient", not with the managed one.

The following should work:

// Merge detached patient
$managedPatient = $em->merge($patient);

// Associate new doctor with patient
$doctor->patients->add($managedPatient);
$managedPatient->doctor = $doctor;

// Persist new doctor and flush
$em->persist($doctor);
$em->flush();
Comment by Dave Keen [ 16/May/10 ]

You are quite right - that does work.

However, I am now trying to implement my use case (turning a tree of detached objects into a tree of managed objects) and implementing the correct order you describe above seems to cause another problem. I am not sure if this should be another ticket, but I'll put it here for the moment.

Note that the part within the stars that creates the unmanaged doctor and the detached patient simulates exactly what is received by Doctrine in my application so I can't put any merges in here.

/********************************************************************/
// This is a new element
$doctor = new \vo\Doctor(); $doctor->name = "New doctor";

// This is a detached element which is in the database
$patient = new \vo\Patient(); $patient->name = "Existing patient"; $patient->id = 1;

$doctor->patients->add($patient); $patient->doctor = $doctor;
/********************************************************************/

// Now replace $patient with its managed version
$managedPatient = $em->merge($patient);
$doctor->patients->set(0, $managedPatient);

// Persist the doctor
$em->persist($doctor);

$em->flush();

This works up to the flush, which throws an error of the form:

Notice: Undefined index: 000000007dd346c3000000005d0908d2 in \Doctrine\ORM\UnitOfWork.php on line 1955

In the database this results in a new doctor being created, but doctor_id in the patients table is set to NULL for the patient that is supposed to be linking to it.

Comment by Benjamin Eberlei [ 06/Jun/10 ]

I think this can't work, because obviously $doctor->patients still points to the unmanaged $patient, not the managed one.

Can you elaborate on why the star part is done by Doctrine? Where is doctrine doing that? what are you doing with the public API?

All the detached entities should be merged before doing anything regarding a NEW entity in my opinion.

Comment by Benjamin Eberlei [ 06/Jun/10 ]

Moved to beta3 for now

Comment by Benjamin Eberlei [ 06/Jun/10 ]

Patch with test-case for this merging scenario

Comment by Roman S. Borschel [ 30/Jul/10 ]

Fixed in http://github.com/doctrine/doctrine2/commit/69073c4b37ee28f988306db4965f512b70f45181





[DDC-576] New entities must have primary key values right after flushing with IDENTITY strategy Created: 07/May/10  Updated: 08/May/10  Resolved: 08/May/10

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-BETA1
Fix Version/s: 2.0-BETA2
Security Level: All

Type: Bug Priority: Critical
Reporter: Václav Novotný Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None
Environment:

PostgreSQL 8.4.3, Ubuntu 10.04


Attachments: GZip Archive example.tar.gz    

 Description   

After insertion of some new entity the primary key must be set. Example code is attached above.



 Comments   
Comment by Roman S. Borschel [ 07/May/10 ]

I think I reproduced this already. Seems to be related to PostgreSQL + IDENTITY only. The SequenceIdentityGenerator must be used but apparently it is not used.

Thanks for the report. Will keep you updated.

ps. The standalone reproduce scripts are good. Thanks for that! If you are interested it would be even better if the test code would be provided as a unit test or with some additional comments and/or assertions about what the desired behavior is or where the supposedly wrong behavior is (even if it is very obvious, like in this issue).





[DDC-561] Metadata caching broken due to incomplete __sleep functions Created: 30/Apr/10  Updated: 30/Apr/10  Resolved: 30/Apr/10

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

Type: Bug Priority: Critical
Reporter: Nico Kaiser Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None

Attachments: Text File ddc-561.patch    

 Description   

When using a persistent Metadata cache, the serialized ClassMetadata objects are not complete.

This leads to very strange behavior since not all Metadata is loaded in the next request (which uses cached Metadata). The problem is that the __sleep methods of Doctrine\ORM\Mapping\AssociationMapping and Doctrine\ORM\Mapping\ClassMetadata are note complete (missing "namespace", "fetchMode" properties).



 Comments   
Comment by Nico Kaiser [ 30/Apr/10 ]

This patch fixes the issue for AssociationMapping and ClassMetadata. I'm not sure if there are more properties missing...

Comment by Roman S. Borschel [ 30/Apr/10 ]

Ouch, bad oversight. Sorry for that. We do actually have tests for serializing and unserializing the metadata, obviously not enough... will fix it asap.

Comment by Roman S. Borschel [ 30/Apr/10 ]

Fixed in http://github.com/doctrine/doctrine2/commit/db2be55e27c87fa513073b2bf44456f1d1423582 .

Thanks for your help.

Comment by Benjamin Eberlei [ 30/Apr/10 ]

Should we re-release Beta1? This is pretty serious and might annoy people

Comment by Roman S. Borschel [ 30/Apr/10 ]

Hehe, no its fine. You can easily patch it manually if needed and beta2 is only a few weeks away.

Comment by Roman S. Borschel [ 30/Apr/10 ]

And you can just use HEAD and not the tag, of course





[DDC-531] Collections broken in self-referenced Entities Created: 20/Apr/10  Updated: 23/Mar/14  Resolved: 23/May/10

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

Type: Bug Priority: Critical
Reporter: Nico Kaiser Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None

Attachments: File DDC531Test.php    
Sub-Tasks:
Key
Summary
Type
Status
Assignee
DDC-597 Add check for public properties in Va... Sub-task Resolved Benjamin Eberlei  

 Description   

When dealing with parent / children entities, the UnitOfWork does not always hydrate all data correctly.

This example generates Group1 and its child Group2. Then Clears the Entity Manager, loads Group2 (so it is in the EM), loads Group1 and then the children of Group1 (Group2 is the child of Group1).
However the children of Group1 cannot be loaded, because $group4->children is not there:

Warning: Invalid argument supplied for foreach() in /Users/nico/Projects/test/test.php on line 20

When calling Debug::dump($group4), I get this:

object(stdClass)#56 (2) {
  ["__CLASS__"]=>
  string(26) "Proxies\EntitiesGroupProxy"
  ["id"]=>
  string(1) "1"
}

test.php
http://pastebin.com/7Q3wwtn6

Group entity:
http://pastebin.com/hBj2Emrf



 Comments   
Comment by Nico Kaiser [ 20/Apr/10 ]

If I clear the Entity Manager between lines 17 and 18, it works... Seems like the previously loaded Group is reused (which is perfectly fine), but its associations (or at least its self-referenced associations) are not loaded (neither proxies are generated)...

Comment by Roman S. Borschel [ 23/Apr/10 ]

Thanks for reporting. I will take a look as soon as I find the time.

Comment by Nico Kaiser [ 23/Apr/10 ]

Test case for Doctrine\Tests\ORM\Functional\Ticket

Comment by Christian Heinrich [ 07/May/10 ]

It might be worth noting that, after renaming $parent to $parent2, the object is loaded but $item4->children remains empty.

If $item3 isn't being fetched beforehands, then everything seems to work fine.

Comment by Christian Heinrich [ 12/May/10 ]

After investigating, it came to my mind that the test submitted uses

$proxy->publicProperty

instead of

$proxy->getPublicProperty()

Therefore, the proxy is not initialized and thus we get unexpected behaviour. Adding a getter a la "getChildren()" and calling this method only, everything works fine.

Therefore, I mark this ticket as invalid.

Comment by Nico Kaiser [ 12/May/10 ]

Shouldn't these properties be automagically instantiated? In our project, we did use getChildren() and it did not work either (sorry, can't provide test case now, will do on monday).

I think collections are populated automatically everywhere (you can always use $this->children in entities), so this should work here as well.

Comment by Christian Heinrich [ 12/May/10 ]

The problem here is, that you're not really using an entity but a proxy object. A proxy object does not initialize its collections, see here: http://www.doctrine-project.org/documentation/manual/2_0/en/best-practices#don%27t-use-public-properties-on-entities

As long as you're using normal entities, the PersistentCollections will normally lazy load, thats true. But as soon as you're using proxies - like in this case - you're running into severe problems. I strongly recommend not using public properties.

Comment by Nico Kaiser [ 17/May/10 ]

You are right - if I use getChildren and a "protected $children", this example works.
However, if I use inheritance (e.g. SINGLE_TABLE), it breaks again, even if I don't use sub items. I'll update the test case.

Comment by Nico Kaiser [ 17/May/10 ]

Updated DDC531Test.php to use SINGLE_TABLE inheritance. Breaks again, even if I don't use public members for the collection...

Comment by Christian Heinrich [ 17/May/10 ]

Hi Nico,

thanks for your response. I will take a look at this issue shortly and will hopefully resolve it before beta2.

regards
christian

Comment by Roman S. Borschel [ 20/May/10 ]

Thanks for your investigation. I tracked down the issue and have a fix pending.

Note though, that with such an example as in the provided testcase, the parents can never be lazy. That means all parents will be eagerly loaded. Of course you can work around that by eager-joining them in DQL or by using Query::HINT_FORCE_PARTIAL_LOAD and things like that.

The reason why the parents in the example can not be lazy is because a parent can potentially be of any subtype, so you would not know which proxy to put in. In general, a single-valued association that points to another entity that has mapped subclasses can not be lazy. This "problem" does not occur when the targeted entity has no mapped subclasses (this means it either does not participate in a mapped inheritance hierarchy or it is a leaf in the hierarchy).

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

Comment by Roman S. Borschel [ 23/May/10 ]

Fixed in http://github.com/doctrine/doctrine2/commit/616f2eda0af1a15ba205cc5013b5f001c34dfc55

Comment by Doctrine Bot [ 23/Mar/14 ]

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





[DDC-500] Single Table Inheritance Selects Created: 07/Apr/10  Updated: 26/Apr/10  Resolved: 26/Apr/10

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-BETA1
Fix Version/s: 2.0-BETA1
Security Level: All

Type: Bug Priority: Critical
Reporter: Michael Ridgway Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None

Attachments: File DDC500Test.php    
Issue Links:
Reference
is referenced by DDC-497 find() and findAll() on Repository do... Closed

 Description   

We have a set of models that use Single Table inheritance and we are trying to select all objects of one type:

/**
 * @Entity
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorColumn(name="type", type="string")
 * @DiscriminatorMap({"Child"="Child", "OtherChild"="OtherChild"})
*/
abstract class ParentModel
{
    /**
     * @Id @Column(name="id", type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /** @Column(type="string") */
    public $property;

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

abstract class SubParent extends ParentModel
{
}

/**
 * @Entity
 */
class Child extends SubParent
{
    /** @Column(type="string") */
    public $anotherProperty;
}

/**
 * @Entity
 */
class OtherChild extends SubParent
{
    /** @Column(type="string") */
    public $someOtherProperty;
}

Now to query for all of the Child objects we do:

$children = $em->getRepository('Child')->findall();
foreach($children AS $child) {
    echo $child->getId();
}

but we get "Notice: Undefined index: id in ./Doctrine/ORM/UnitOfWork.php on line 1727" on the finAll() call and the objects that aren't of the correct type have their properties nulled out. This is because the query that is being executed doesn't have any conditionals for the type of model it's looking for and the ORM doesn't check to make sure that the object is of the correct type.

This could be solved by having conditionals in the SQL query (chaining a bunch of 'or' statements for all of the child objects) or by pulling back all of the objects and then filtering out what isn't of the correct type. Unfortunately neither solution seems ideal.

I'll try to make a test case for this then.



 Comments   
Comment by Michael Ridgway [ 07/Apr/10 ]

Adding another child class just to be clear.

Comment by Roman S. Borschel [ 07/Apr/10 ]

Related to DDC-497 ? Of course there should be conditionals in the query when querying for a subtype. It really surprises me that this seems not to be the case. Maybe there has been some regression.

Comment by Michael Ridgway [ 07/Apr/10 ]

Attached a unit test that may or may not work.

It looks to be a similar issue for sure.

Comment by Michael Ridgway [ 08/Apr/10 ]

Fixed test case. Now gives the 'Undefined index: id' error.

Comment by Roman S. Borschel [ 19/Apr/10 ]

Reproduced successfully and working on it.

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

Fixed in http://github.com/doctrine/doctrine2/commit/760ea34a0cc3cae4e3caea17e8aab6ceb74ecace





[DDC-497] find() and findAll() on Repository do not work when SINGLE_TABLE inheritance is used Created: 05/Apr/10  Updated: 26/Apr/10  Resolved: 26/Apr/10

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA4
Fix Version/s: 2.0-BETA1
Security Level: All

Type: Bug Priority: Critical
Reporter: Marcus Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None
Environment:

MacOsX 10.6.2 - Zend Server 4.0.6 - PHP 5.3 - MySql 5.1.40


Issue Links:
Reference
relates to DDC-500 Single Table Inheritance Selects Closed

 Description   
 
Class Orm\Models\Car:

	@Entity
	@Table(name="cars")
	@InheritanceType("SINGLE_TABLE")
 	@DiscriminatorColumn(name="discr", type="string")
	@DiscriminatorMap({"car" = "Orm\Models\Car", "bluecar" = "Orm\Models\BlueCar"})

Class Orm\Models\BlueCar extends Orm\Models\Car:
	
	@Entity

Now my Database holds 4 records:
	
	id 	title 		discr
	1 	blue car 	bluecar
	2 	only Car 	car
	5 	blue car2 	bluecar
	6 	only Car2 car

Now querying objects by Repository leads to some errors.

	
	//quering for all BlueCars
	$em->getRepository('Orm\Models\BlueCar')->findAll();
	
	//the result set counts 4 objects
	blue car	: Orm\Models\BlueCar
			: Orm\Models\Car
	blue car2	: Orm\Models\BlueCar
			: Orm\Models\Car

	//The 2 Car Items where the title is missing are to much for this result set, and useless
	// there is also a php notice coming up for each Orm\Models\Car object
	Notice: Undefined index: id in /library/Doctrine/ORM/UnitOfWork.php  on line 1727
	I use mysql as Database and so the sql query looks like this.

	"SELECT c0.id AS id1, c0.title AS title2, discr FROM cars c0"
	
	It seems that the query is missing the where discriminator = "bluecar" part

querying for Car
	$em->getRepository('Orm\Models\Car')->findAll();
	
	blue car: Orm\Models\BlueCar
	only Car: Orm\Models\Car
	blue car2: Orm\Models\BlueCar
	only Car2: Orm\Models\Car

	Is working without errors but i think it is a mere chance if you look at the query
	"SELECT c0.id AS id1, c0.title AS title2, discr FROM cars c0" it is the same.

	I am not shure if it is intended that quering for Cars also returns BlueCars but due to the behavior when using DQL for quering, i guess it is right.
	That means, when using DQL:

	$q = $em->createQuery('select u from Orm\Models\BlueCar u');
	$results = $q->execute();

	everything works as expected, so using a custom EntityRepository and override find, findAll and so on is a workaround. So this is a minor bug ?


 Comments   
Comment by Roman S. Borschel [ 05/Apr/10 ]

You mention ALPHA4 as the affected version. Did you test this with trunk?

Comment by Roman S. Borschel [ 05/Apr/10 ]

@"I am not shure if it is intended that quering for Cars also returns BlueCars but due to the behavior when using DQL for quering, i guess it is right."

Of course. Anything else would be wrong. If you query for cars you get all cars. BlueCars are Cars.

Comment by Marcus [ 07/Apr/10 ]

Tested with Revision: 7533.

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

Fixed in http://github.com/doctrine/doctrine2/commit/760ea34a0cc3cae4e3caea17e8aab6ceb74ecace





[DDC-481] Incorrect table aliasing when using quoting on table names Created: 29/Mar/10  Updated: 14/Jun/10  Resolved: 08/May/10

Status: Closed
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers, ORM
Affects Version/s: 2.0-ALPHA4
Fix Version/s: 2.0-BETA2
Security Level: All

Type: Bug Priority: Critical
Reporter: Menno Luiten Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None
Environment:

Doctrine trunk (r7479)


Attachments: Text File DDC-481.patch    

 Description   

I need to quote several table names (because of reserved words within MySQL) like so:

 
/**
 * @Entity
 * @Table(name="`Column`")
 */
class Column extends OptionAbstract

Another entity Question is related one-to-many to these entities, however, when trying to fetch the relation I get SQL errors because it seems to use the backtick as the table alias, which is illegal. An example of the query it's generating:

SELECT `0.id AS id1, `0.name AS name2, `0.sequence AS sequence3, `0.question_id AS question_id4 FROM `Column` `0 WHERE question_id = ?


 Comments   
Comment by Menno Luiten [ 29/Mar/10 ]

Here's a patch that works for me; looping through the table name until there is a character in the range a-z (case insensitive) to use as an alias.

Might need some more error-reporting and endless loop protection etc.

Comment by Roman S. Borschel [ 29/Mar/10 ]

Thanks but the problem is elsewhere. The table name should not have the quote characters. The quote characters should be stripped during metadata parsing and instead a flag quoted => true set for the table in ClassMetadata::$table. Its not hard to fix, we will look into it soon.





[DDC-448] Cannot select rows from chield table by JoinColumn in @InheritanceType("JOINED") parent table Created: 20/Mar/10  Updated: 13/Apr/10  Resolved: 12/Apr/10

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

Type: Bug Priority: Critical
Reporter: Uvarov Michael Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None


 Description   

This bug is connected with http://www.doctrine-project.org/jira/browse/DDC-416
I have this schema.

/**
 * @Entity
 * @InheritanceType("JOINED") 
 * @DiscriminatorColumn(name="discr", type="smallint")
 * @DiscriminatorMap({
 * "0" = "mainTable",
 * "1" = "SubTable"
 * })
 */
class mainTable
{  	
    /**
     * @Id
     * @Column(name="id", type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ManyToOne(targetEntity="connectedClass",  cascade={"all"}, fetch="EAGER")
     * @JoinColumn(name="connectedClassId", referencedColumnName="id", onDelete="CASCADE", onUpdate="CASCADE", nullable=true)
     */
    private $connectedClassId;
}

/**
 * @Entity
 * @Table(name="connectedClass")
 * @HasLifecycleCallbacks
 */
class connectedClass
{	
    /**
     * @Id
     * @Column(name="id", type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    protected $id; // connected with mainTable
}

/**
 * @Entity
 * @Table(name="SubTable")
 */
class SubTable extends mainTable
{
}


$qb->select(array('b'))
       ->from('SubTable', 'b')
       ->where(
           $qb->expr()->eq('b.connectedClassId', '?1') // select by JoinColumn field does not work
                                                                                          // select by normal column work (after http://www.doctrine-project.org/jira/browse/DDC-416  ) 
       )
       ->setParameter(1, $value); // $value - const or connectedClass object


Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'i1_.connectedClassId' in 'where clause'' in /var/www/shelly/library/Doctrine/DBAL/Connection.php:573
Stack trace:
#0 /var/www/shelly/library/Doctrine/DBAL/Connection.php(573): PDOStatement->execute(Array)
#1 /var/www/shelly/library/Doctrine/ORM/Query/Exec/SingleSelectExecutor.php(42): Doctrine\DBAL\Connection->execute('SELECT p0_.id A...', Array)
#2 /var/www/shelly/library/Doctrine/ORM/Query.php(231): Doctrine\ORM\Query\Exec\SingleSelectExecutor->execute(Object(Doctrine\DBAL\Connection), Array)
#3 /var/www/shelly/library/Doctrine/ORM/AbstractQuery.php(514): Doctrine\ORM\Query->_doExecute(Array)
#4 /var/www/shelly/library/Doctrine/ORM/AbstractQuery.php(391): Doctrine\ORM\AbstractQuery->execute(Array, NULL)

So, we cannot select rows by JoinColumn from Inheritance tables, because doctrine selects SubTable.connectedClassId field, not mainTable.connectedClassId

This bug was fix in http://www.doctrine-project.org/jira/browse/DDC-416 patch, but it was not commited. I may write unit test for this problem



 Comments   
Comment by Guilherme Blanco [ 12/Apr/10 ]

In http://github.com/doctrine/doctrine2/commit/56a8f5cd5353908b815607a6e089201c95e01e6c this issue was fixed!

Thanks for the report!

Comment by Roman S. Borschel [ 13/Apr/10 ]

The testcase is irritating though, because connectedClassId is an object, not an id.





[DDC-419] Problem when I make a INNER JOIN between 2 classes Created: 12/Mar/10  Updated: 08/Aug/10  Resolved: 08/Aug/10

Status: Closed
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: 2.0-ALPHA4
Fix Version/s: 2.0-BETA4
Security Level: All

Type: Bug Priority: Critical
Reporter: Henrique Girardi dos Santos Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None
Environment:

Ubuntu 9.10
PHP 5.3.1-0.dotdeb.1 with Suhosin-Patch (cli) (built: Dec 5 2009 20:08:29)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies
with Xdebug v2.0.5, Copyright (c) 2002-2008, by Derick Rethans
with Suhosin v0.9.29, Copyright (c) 2007, by SektionEins GmbH
PHPUnit 3.4.6 by Sebastian Bergmann


Attachments: File DDC419Test.php     File TestCase.tar.bz2    
Issue Links:
Dependency
depends on DDC-522 Join columns can not be named the sam... Closed

 Description   

I hae some problems when I make a inner join between 2 classes, one of these classes makes join to others 2 classes in the same time and when I try to make a inner to this class, it's not coming like a object, but object Id...

I don't know why its happening..

I make a test case..there're all the classes and yml that show my problem..it's on ItemPregaoTest.php.. just need to run phpunit in this file..



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

This is what returns for me:

object(stdClass)[82]
  public '__CLASS__' => string 'ItemPregao' (length=10)
  public 'id' => int 1
  public 'item' => string '1' (length=1)

The expected result I guess. What happens for you?

Comment by Henrique Girardi dos Santos [ 14/Mar/10 ]

Ok...this is what happen for me...
but I think the expected result would be

object(stdClass)[82]
  public '__CLASS__' => string 'ItemPregao' (length=10)
  public 'id' => int 1
  public 'item' => string 'Item' (length=4)

because 'public item' makes refereces to Item class, so I think it should give me a Item class, not its Id...

Comment by Henrique Girardi dos Santos [ 16/Mar/10 ]

When I try to make a inner join between Item and ItemPregao, happens what I've said before, but if I make a inner join between Item and its refereces tables, it's working fine

$qb = $this->em->createQueryBuilder();
        $qb->select('i, cc, ca, cl')
           ->from('Item', 'i')
           ->innerJoin('i.classificacaoCatalogo', 'cc')
           ->innerJoin('cc.catalogo', 'ca')
           ->innerJoin('cc.classificacao', 'cl')
        ;

object(stdClass)[141]
  public '__CLASS__' => string 'Item' (length=4)
  public 'id' => int 1
  public 'descricao' => string 'ITEM 1' (length=6)
  public 'classificacaoCatalogo' => 
    object(stdClass)[99]
      public '__CLASS__' => string 'ClassificacaoCatalogo' (length=21)
      public 'id' => int 1
      public 'classificacao' => string 'Classificacao' (length=13)
      public 'catalogo' => string 'Catalogo' (length=8)

It brings a class on 'classificacaoCatalogo' and inside classificacaoCatalogo you can see that 'classificacao' and 'catalogo' are objects too..so it worked! But If I make this:

$qb = $this->em->createQueryBuilder();
        $qb->select('ip, i')
           ->from('ItemPregao', 'ip')
           ->innerJoin('ip.item', 'i');

do not work like before..

object(stdClass)[152]
  public '__CLASS__' => string 'ItemPregao' (length=10)
  public 'id' => int 1
  public 'item' => int 1

'item' should be a object, not a integer..

Comment by Benjamin Eberlei [ 16/Mar/10 ]

Ah now I see it. Yes, this seems to be a problem.

Comment by Benjamin Eberlei [ 18/Mar/10 ]

I have taken some time now trying to re-produce it, there is definately a bug i have identified, however i havent found the reason yet.

Comment by Henrique Girardi dos Santos [ 18/Mar/10 ]

ok man!
I've try to find the reason too but I havent found yet too...
I dont know if there's something about the item are conected to a table that there're 2 table...
i dont know :S

Comment by Benjamin Eberlei [ 20/Mar/10 ]

I found the issue. A quick fix is to rename the join column to "item_id" instead of "item". This is causing the bug, we will look how to fix it.

@Roman:

This is particularly nasty, in UnitOfWork::createEntity the join column is set to the field name in $data, which makes the following code write the primitive FK value to the entity:

            if ($this->_useCExtension) {
                doctrine_populate_data($entity, $data);
            } else {
                foreach ($data as $field => $value) {
                    if (isset($class->reflFields[$field])) {
                        $class->reflFields[$field]->setValue($entity, $value);
                    }
                }
            }

This then leads in the ObjectHydrator to:

                    // PATH B: Single-valued association
                    $reflFieldValue = $reflField->getValue($parentObject);
                    if ( ! $reflFieldValue || isset($this->_hints[Query::HINT_REFRESH])) {

not evaluating to null, but to the primitive value. the If condition does not match here and the relation is never set.

A simple solution would be to replace !$reflFieldValue with !is_object().

Comment by Benjamin Eberlei [ 20/Mar/10 ]

Attached a reproduce test-case.

Comment by Roman S. Borschel [ 20/Mar/10 ]

I see. As their is an easy workaround, this is not a blocker, however.

Comment by Roman S. Borschel [ 15/Apr/10 ]

DDC-522 needs to be fixed, then this issue is solved, too (its the same after all, the other issue is just more specific).

Comment by Roman S. Borschel [ 15/Apr/10 ]

Scheduled for beta2

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

Should be fixed now in master.





[DDC-388] Private properties in @MappedSupperclass don't work Created: 03/Mar/10  Updated: 14/Apr/10  Resolved: 14/Apr/10

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

Type: Bug Priority: Critical
Reporter: Jaka Jancar Assignee: Roman S. Borschel
Resolution: Fixed Votes: 2
Labels: None
Environment:

PHP 5.3.1


Issue Links:
Duplicate
is duplicated by DDC-456 Wrong implementation of loading metad... Closed

 Description   

All of my entites extend an abstract class Model to inherit the 'id' property and some other functionality. It has the @MappedSuperclass annotation.

If the id property is declared private to the Model class, I'll get the following exception when using entites extending it:

[03-Mar-2010 11:36:29] exception 'ReflectionException' with message 'Property id does not exist' in library/Doctrine/ORM/Mapping/ClassMetadata.php:370
Stack trace:
#0 library/Doctrine/ORM/Mapping/ClassMetadata.php(370): ReflectionClass->getProperty('id')
#1 [internal function]: Doctrine\ORM\Mapping\ClassMetadata->__wakeup()
...

I haven't looked at Doctrine code, but perhaps you should be looking for the property on the class which actually has the @Column annotation?



 Comments   
Comment by Roman S. Borschel [ 03/Mar/10 ]

Yes, I think the 'inherited' key is simply not set for fields that are inherited from mapped superclasses. This needs to be fixed.

Comment by Roman S. Borschel [ 14/Apr/10 ]

Fixed in http://github.com/doctrine/doctrine2/commit/d4232d906e433b1fe4dd8aa85aa7a4aca3a2cf4c .
Make sure to clear the metadata cache if necessary.





[DDC-335] Refactor DQL EBNF to use JOIN FETCH as syntax for fetch joins only Created: 14/Feb/10  Updated: 19/Feb/10  Resolved: 19/Feb/10

Status: Closed
Project: Doctrine 2 - ORM
Component/s: DQL
Affects Version/s: 2.0-ALPHA4
Fix Version/s: 2.0-BETA1
Security Level: All

Type: Improvement Priority: Critical
Reporter: Benjamin Eberlei Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None

Issue Links:
Dependency
is required for DDC-195 Ordering of associations Resolved

 Description   

There are several problems with the current approach on fetch joins:

1. There is no way to determine in the parser already if a join is fetch or not, this makes it much harder to implement things like @OrderBy or @OrderColumn
2. A DQL like "SELECT u, g.name FROM User u JOIN u.group g" currently tries to partially load the group object instead of just returning g.name as scalar. This is very unintuiative.

Solution, change the EBNF too:

Join                                       ::= ["LEFT" ["OUTER"] | "INNER"] "JOIN" [FETCH] JoinAssociationPathExpression 
                                               ["AS"] AliasIdentificationVariable [("ON" | "WITH") ConditionalExpression]

Question would be how to specify partial object selects.

Romans idea was something like:

select u.{name, other, field, stuff}

However my take is this would again put information into the select clause that might be interesting elsewhere, so

SELECT u FROM User u JOIN FETCH u.group PARTIAL id, name

That way we could add both $isFetchJoin and $isPartial flags to the AST/Join Node plus an additional $partialFields array.



 Comments   
Comment by Benjamin Eberlei [ 16/Feb/10 ]

Ah just to remember, the idea on the partial fetch syntax was something like:

select u FROM User u.{name, other, field, stuff} JOIN FETCH u.group g.{id, name, baz}
Comment by Benjamin Eberlei [ 16/Feb/10 ]

I think this will also make the HINT_PARTIAL_LOAD constant obsolet, since the DQL is already implicitly requesting a partial load.

Comment by Roman S. Borschel [ 16/Feb/10 ]

Regarding HINT_FORCE_PARTIAL_LOAD: Not necessarily, but it might need to be renamed since its still used to decide whether to stub associations with empty collections/proxies.

Anyways, I've played around a bit with different implementations in the last days and I changed my mind regarding changing the fetch join syntax. It has many complications, like more difficult sql construction in the walker, among other things, and of course the fact that it would be a huge bc break.

However, some things will change. "select u.name" will select a scalar value, as you expect. The new syntax for partial object selection will currently be:

select partial u.{id,name}, partial a.{id,city} from User u join u.address a

There will be a new AST node PartialObjectExpression that represents such a construct.

Thats the current state of my progress. Regarding the isFetchJoin/isPartial decisions, we need to find another way and I'm confident there are some other ways.

So far...

Comment by Benjamin Eberlei [ 16/Feb/10 ]

If we change u.name to retrieving a scalar value always its easy to get all the fetch joins identification variables inside the SELECT already:

If (identificiationVariable) => fetchJoin

Then when the join is found, you can mark the Join as Fetch already.

Comment by Roman S. Borschel [ 19/Feb/10 ]

Implemented.





[DDC-317] Using a function only in hydration returns only one result Created: 11/Feb/10  Updated: 19/Feb/10  Resolved: 19/Feb/10

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA4
Fix Version/s: 2.0-BETA1
Security Level: All

Type: Bug Priority: Critical
Reporter: Benjamin Eberlei Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None


 Description   

Output of $arg:

array(1) {
  [-1]=>
  array(1) {
    ["namedep"]=>
    string(25) "Jonathan W.Administration"
  }
}
    public function testConcatFunction()
    {
        $this->generateFixture();
        $arg = $this->_em->createQuery('SELECT CONCAT(m.name, m.department) AS namedep FROM Doctrine\Tests\Models\Company\CompanyManager m')
                         ->getArrayResult();

        $this->assertEquals(4, count($arg)); // fails with 1
    }

    protected function generateFixture()
    {
        $manager1 = new CompanyManager();
        $manager1->setName('Roman B.');
        $manager1->setTitle('');
        $manager1->setDepartment('IT');
        $manager1->setSalary(100000);

        $manager2 = new CompanyManager();
        $manager2->setName('Benjamin E.');
        $manager2->setTitle('');
        $manager2->setDepartment('HR');
        $manager2->setSalary(200000);

        $manager3 = new CompanyManager();
        $manager3->setName('Guilherme B.');
        $manager3->setTitle('');
        $manager3->setDepartment('Complaint Department');
        $manager3->setSalary(400000);

        $manager4 = new CompanyManager();
        $manager4->setName('Jonathan W.');
        $manager4->setTitle('');
        $manager4->setDepartment('Administration');
        $manager4->setSalary(800000);

        $this->_em->persist($manager1);
        $this->_em->persist($manager2);
        $this->_em->persist($manager3);
        $this->_em->persist($manager4);
        $this->_em->flush();
        $this->_em->clear();
    }


 Comments   
Comment by Benjamin Eberlei [ 11/Feb/10 ]

Additional bug, changing the DQL to:

SELECT CONCAT(m.name, m.department) AS namedep FROM Doctrine\Tests\Models\Company\CompanyManager m WHERE m.id = 4

returns an empty result.

Comment by Benjamin Eberlei [ 11/Feb/10 ]

Thie following DQL gives a partial error bug:

SELECT m, m.salary+2500 AS add FROM Doctrine\Tests\Models\Company\CompanyManager m

Error:

Doctrine\Tests\ORM\Functional\QueryDqlFunctionTest::testOperatorAdd()
Exception: [Doctrine\Common\DoctrineException] Loading partial objects is dangerous. Fetch full objects or consider using a different fetch mode. If you really want partial objects, set the doctrine.forcePartialLoad query hint to TRUE.
Comment by Benjamin Eberlei [ 11/Feb/10 ]

The same goes for - * and /

Comment by Benjamin Eberlei [ 13/Feb/10 ]

Generated SQL of the CONCAT Example:

SELECT CONCAT(c0_.name, c1_.department) AS sclr0 FROM company_managers c2_ INNER JOIN company_employees c1_ ON c2_.id = c1_.id INNER JOIN company_persons c0_ ON c2_.id = c0_.id
Comment by Roman S. Borschel [ 19/Feb/10 ]

Should be fixed now.





[DDC-263] YAML and XML Driver do not support cascading options "all", "detach". Also: Improvement of YAML Syntax (Patch attached) Created: 19/Jan/10  Updated: 22/Jan/10  Resolved: 22/Jan/10

Status: Closed
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers
Affects Version/s: 2.0-ALPHA3
Fix Version/s: 2.0-ALPHA4
Security Level: All

Type: Bug Priority: Critical
Reporter: Christian Heinrich Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None

Attachments: Text File MappingDriversCascade.patch     Text File MappingDriversCascade.patch     Text File YamlDriver_change_cascade_syntax.php.patch    

 Description   

Hi there,

I've attached a small patch which addresses the following issues:

-> YAML did not support cascading options "all" (as described in documentation) and "detach" (as used in AssociationMapping class). The attached patch fixes that.

-> XML does not support these things either, but the attached patch DOES NOT FIX THAT (see below).

Also addressed:

YAML had syntax like cascadeRemove, cascadePersist etc., but the documentation for the annotation driver uses only "persist, remove" etc.

This patch changes the syntax to the following:

cascade: [ persist, remove ]

OR

cascade:

  • persist
  • remove

(Both work!)

It is now also possible to use cascade: [all]

The YAML Driver was changed in that way that he must not know about the currently supported cascate actions. This has been pushed towards the AssociationMapping and I strongly believe that this is the right way.

On the other hand, I did not change the XML Driver functionality. It does still know about the cascade actions and does most probably not support the detach and "all" actions. That should be fixed, but won't take too long.



 Comments   
Comment by Christian Heinrich [ 22/Jan/10 ]
  • YAML Driver fixed.
  • XML Driver fixed (supports now both cascade-persist and (because the other drivers do not use the prefixed cascade-) single "persist")
  • I've modified the UnitTests to cover cascade="all" for XML & YAML
Comment by Roman S. Borschel [ 22/Jan/10 ]

That patch looks good but there seem to be tabs in your patches. Please make sure that you use "soft tabs" (4 spaces) in your editor.

Comment by Christian Heinrich [ 22/Jan/10 ]

Resolved tab issue.

Comment by Roman S. Borschel [ 22/Jan/10 ]

Patch applied. Thanks! So this will be included in todays ALPHA4 release.





[DDC-222] Create unit tests for CLI components Created: 22/Dec/09  Updated: 16/Apr/14  Resolved: 16/Apr/14

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA3
Fix Version/s: 2.x
Security Level: All

Type: Task Priority: Critical
Reporter: Roman S. Borschel Assignee: Guilherme Blanco
Resolution: Invalid Votes: 0
Labels: None

Issue Links:
Reference
is referenced by DDC-359 Specified, but empty CLI Options --op... Resolved

 Comments   
Comment by Roman S. Borschel [ 19/May/10 ]

Whats the status here? Do we have any?

Comment by Guilherme Blanco [ 19/May/10 ]

Since we moved to Symfony Console I don't think this is needed anymore.
The purpose of this ticket was actually to test our own CLI support, which was dropped.

I'm closing the ticket due to this. Reopen if you have any other comment.

Comment by Benjamin Eberlei [ 20/May/10 ]

I think we do need some basic functional tests of our Commands, they have been subject to many bugs in the past becaues they are not tested.

Comment by Benjamin Eberlei [ 19/Jun/10 ]

Fixed another fatal error in the command due to missing namespace dependency. We need tests for all the commands, there have been dozens of issues on these things so far.

This commit shows a simple approach on how testing is easily possible for symfony commands:

http://github.com/doctrine/doctrine2/commit/51e6681934a7cf4448b85c5670c04045f66c6056

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

Can we expect some more tests for beta4 or is it unlikely that you find the time? Should we move this further back or does someone else want to step in?

Comment by Guilherme Blanco [ 16/Apr/14 ]

This is not valid anymore as we use Symfony CLI component





[DDC-193] Remove ClassMetadataInfo#inverseMappings Created: 06/Dec/09  Updated: 10/Apr/10  Resolved: 10/Apr/10

Status: Closed
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers, ORM
Affects Version/s: 2.0-ALPHA3
Fix Version/s: 2.0-BETA1
Security Level: All

Type: Improvement Priority: Critical
Reporter: Roman S. Borschel Assignee: Roman S. Borschel
Resolution: Fixed Votes: 1
Labels: None

Attachments: Text File ddc193.patch    

 Description   

The ClassMetadataInfo#inverseMappings attribute is an unnecessary complication.

The problem comes down to: "Given an association $assoc, how do I know if the association is bidirectional?".

If $assoc is the inverse side ($assoc->isInverseSide()), its clear, its bidirectional. But if $assoc is the owning side, we dont know.
What we currently do to determine that in such a case looks as follows:

            if (isset($targetClass->inverseMappings[$assoc->sourceEntityName][$assoc->sourceFieldName])) {
                // Bi-directional
            }

So we check whether the target class has an inverse mapping to the source class. This is quite cumbersome. Additionally, we're usually only interested in the sourceFieldName of the inverse association.

Therefore, it would simplify internal code a lot if we simply introduced a "inversedBy" attribute on an association that is used on the owning side and that corresponds to "mappedBy" on the inverse side. Example:

/** @Entity */
class A {
...
   /**
    * @OneToOne(targetEntity="Other", inversedBy="a")
    * @JoinColumn(name="other_id", referencedColumnName="id")
    */
   private $other;
...
}
...
/** @Entity */
class Other {
    /** @OneToOne(targetEntity="A", mappedBy="other") */
    private $a;
}

This breaks BC. However, I think this is really necessary as it simplifies and speeds up the code, together with removing the inverseMappings attribute altogether.

So this should happen before beta.



 Comments   
Comment by Roman S. Borschel [ 31/Mar/10 ]

Patch is ready and will be committed within the next week.





[DDC-199] collection-valued, polymorphic fetch joins broken (hydration) Created: 07/Dec/09  Updated: 07/Dec/09  Resolved: 07/Dec/09

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA3
Fix Version/s: 2.0-ALPHA4
Security Level: All

Type: Bug Priority: Critical
Reporter: Roman S. Borschel Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None


 Description   

Polymorphic fetch-joins of collections are currently broken in the ObjectHydrator.






[DDC-187] JOIN fails with inherited entities Created: 02/Dec/09  Updated: 03/Dec/09  Resolved: 03/Dec/09

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA3
Fix Version/s: 2.0-ALPHA4
Security Level: All

Type: Bug Priority: Critical
Reporter: Nico Kaiser Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None


 Description   

"Entity\User\AbstractUser" is a base entity for user records, "Entity\User\Person" extends AbstractUser (Single Table inheritance in this case).
The "Setting" property is a OneToOne relation with another entity.

Now when I call this DQL:
SELECT u, t FROM Entity\User\AbstractUser u LEFT JOIN u.Setting t

The ObjectHydrator fails in line 276 ("if ( ! $relation->isOneToOne()) {"...) with "PHP Fatal error: Call to a member function isOneToOne() on a non-object in .../lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php".

It works when using the sub class for the query:
SELECT u, t FROM Entity\User\Person u LEFT JOIN u.Setting t



 Comments   
Comment by Nico Kaiser [ 02/Dec/09 ]

It seems like ObjectHydrator::_hydrateRow tries to find a _ce entry for AbstractUser (but _ce only holds entries for Person)...

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

Does Setting use inheritance also? TopnewsSetting extends Setting? If so which inheritance type?

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

Can we see the classes and their mappings? AbstractUser, User, Setting and TopnewsSetting. Then I can set up a test to reproduce it. Thanks!

Comment by Nico Kaiser [ 02/Dec/09 ]

Oh no I forgot to change TopnewsSetting to Setting in this report, there is no inheritance, just copy & paste bug.

Comment by Nico Kaiser [ 03/Dec/09 ]

Here are the classes and example code:

http://pastie.org/private/ljkiowarvm9trhdyug903q

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

Successfully reproduced in our test suite and working on it.

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

Should be fixed now. Thanks for reporting.





[DDC-171] Cascade persist update foreign key for all unchanged entities Created: 23/Nov/09  Updated: 10/Dec/09  Resolved: 10/Dec/09

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA4
Fix Version/s: 2.0-ALPHA4
Security Level: All

Type: Bug Priority: Critical
Reporter: Eric Durand-Tremblay Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None


 Description   

Using cascade persist, linked entities get updated even if there is no change made.

I get an update on the unchanged foreign key even if I don't modify
the entity at all.

UPDATE email SET client_id = ? WHERE id = ?
$query = $qb->getQuery();
$client = $query->getSingleResult();
$em->flush(); 


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

Can we see the query? I mean the DQL query! Thanks.

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

Nevermind. Got it reproduced.

Comment by Eric Durand-Tremblay [ 09/Dec/09 ]

I tried with revision 6913 and I still reproduce the problem.

Is there anyway I can use your UniTest framework, that way, I could check your test case and maybe suggest improvement.

Comment by Eric Durand-Tremblay [ 09/Dec/09 ]

I managed to run the UnitTests.

Do you have a test for this specific issue ?

Comment by Eric Durand-Tremblay [ 09/Dec/09 ]

Here is my result for Doctrine/Tests/ORM/AllTests.php

1) testOptimisticTimestampSetsDefaultValue(Doctrine\Tests\ORM\Functional\Locking\OptimisticTest)
strtotime(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for 'EST/-5.0/no DST' instead
/home/eric/doctrine_trunk/tests/Doctrine/Tests/ORM/Functional/Locking/OptimisticTest.php:126

2) testOptimisticTimestampFailureThrowsException(Doctrine\Tests\ORM\Functional\Locking\OptimisticTest)
DateTime::createFromFormat(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for 'EST/-5.0/no DST' instead
/home/eric/doctrine_trunk/lib/Doctrine/DBAL/Types/DateTimeType.php:33
/home/eric/doctrine_trunk/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php:225
/home/eric/doctrine_trunk/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php:239
/home/eric/doctrine_trunk/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php:112
/home/eric/doctrine_trunk/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php:102
/home/eric/doctrine_trunk/lib/Doctrine/ORM/AbstractQuery.php:511
/home/eric/doctrine_trunk/lib/Doctrine/ORM/AbstractQuery.php:387
/home/eric/doctrine_trunk/tests/Doctrine/Tests/ORM/Functional/Locking/OptimisticTest.php:136

3) testJoinedSubclassPersisterRequiresSpecificOrderOfMetadataReflFieldsArray(Doctrine\Tests\ORM\Functional\Ticket\DDC168Test)
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'salary' cannot be null
/home/eric/doctrine_trunk/lib/Doctrine/ORM/Persisters/JoinedSubclassPersister.php:190
/home/eric/doctrine_trunk/lib/Doctrine/ORM/UnitOfWork.php:698
/home/eric/doctrine_trunk/lib/Doctrine/ORM/UnitOfWork.php:283
/home/eric/doctrine_trunk/lib/Doctrine/ORM/EntityManager.php:288
/home/eric/doctrine_trunk/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC168Test.php:34
Comment by Roman S. Borschel [ 09/Dec/09 ]

You need to fix your timezone settings but that is unrelated to this problem.

To reproduce it, I added the following test temporarily to Doctrine\Tests\ORM\Functional\BasicFunctionalTest.php:

    public function testFlushDoesNotIssueUnnecessaryUpdates()
    {
        
        $user = new CmsUser;
        $user->name = 'Guilherme';
        $user->username = 'gblanco';
        $user->status = 'developer';
        
        $address = new CmsAddress;
        $address->country = 'Germany';
        $address->city = 'Berlin';
        $address->zip = '12345';
        
        $address->user = $user;
        $user->address = $address;
        
        $this->_em->persist($user);
        
        $this->_em->flush();
        $this->_em->clear();
        
        // show SQL from here on...
        $this->_em->getConnection()->getConfiguration()->setSqlLogger(new \Doctrine\DBAL\Logging\EchoSqlLogger);
        
        
        $query = $this->_em->createQuery('select u, a from Doctrine\Tests\Models\CMS\CmsUser u join u.address a');
        echo "QUERY!".PHP_EOL;
        $user2 = $query->getSingleResult();
        
        echo "FLUSH!".PHP_EOL;
        $this->_em->flush();
        
    }

However, since I did not really know how to check that, keeping this test in didnt make much sense.

Can you try this test? Before my patch it issued an UPDATE query but not after my changes.

It is pretty difficult to test this in an isolated manner.

Comment by Benjamin Eberlei [ 09/Dec/09 ]

First two failures are your fault, you havent set the default timezone in php.ini

The last failure is unrelated, its a benchmark for another bug.

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

OK. Latest trunk contains a test now that verifies that no SQL is executed on the flush.

Can you please tell us how to modify it to reproduce the problem?

Look into: Doctrine/Tests/ORM/Functional/BasicFunctionalTest.php

Last test method.

Comment by Eric Durand-Tremblay [ 09/Dec/09 ]

Got it! Your fix worked on OneToOne relation but not OneToMany

I did the same test using the CmsArticles entity and here is the result :

SELECT c0_.id AS id0, c0_.status AS status1, c0_.username AS username2, c0_.name AS name3, c1_.id AS id4, c1_.topic AS topic5, c1_.text AS text6, c1_.user_id AS user_id7 FROM cms_users c0_ INNER JOIN cms_articles c1_ ON c0_.id = c1_.user_id
FLUSH!
UPDATE cms_users SET name = ? WHERE id = ?
array(2) {
  [0]=>
  string(6) "FooBar"
  [1]=>
  int(17)
}
UPDATE cms_articles SET user_id = ? WHERE id = ?
array(2) {
  [0]=>
  int(17)
  [1]=>
  int(2)
}
DONE!
DELETE FROM cms_users_groups
DELETE FROM cms_groups
DELETE FROM cms_addresses
DELETE FROM cms_phonenumbers
DELETE FROM cms_articles
DELETE FROM cms_users
Comment by Eric Durand-Tremblay [ 09/Dec/09 ]

Dont forget to add the cascade persist for the articles relation

public function testFlushDoesNotIssueUnnecessaryUpdates()
    {

        $user = new CmsUser;
        $user->name = 'Guilherme';
        $user->username = 'gblanco';
        $user->status = 'developer';

        $address = new CmsAddress;
        $address->country = 'Germany';
        $address->city = 'Berlin';
        $address->zip = '12345';

        $article = new \Doctrine\Tests\Models\CMS\CmsArticle();
        $article->text = "Lorem ipsum dolor sunt.";
        $article->topic = "A Test Article!";
        $article->setAuthor($user);
        $user->articles[] = $article;


        $address->user = $user;
        $user->address = $address;

        $this->_em->persist($user);

        $this->_em->flush();
        $this->_em->clear();

        // show SQL from here on...
        $this->_em->getConnection()->getConfiguration()->setSqlLogger(new \Doctrine\DBAL\Logging\EchoSqlLogger);


        //$query = $this->_em->createQuery('select u, a from Doctrine\Tests\Models\CMS\CmsUser u join u.address a');
        $query = $this->_em->createQuery('select u, a from Doctrine\Tests\Models\CMS\CmsUser u join u.articles a');
        echo "QUERY!".PHP_EOL;
        $user2 = $query->getSingleResult();

        $user2->name = "FooBar";

        echo "FLUSH!".PHP_EOL;
        $this->_em->flush();

        echo "DONE!".PHP_EOL;

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

OK. I will look into this later or tomorrow.

Thanks for your help.

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

Should be fixed now (second attempt)

Can you check whether DDC-140 can be closed also?

Comment by Eric Durand-Tremblay [ 10/Dec/09 ]

Yes, this is now fixed for me.
I confirm you this also close DDC-140

Thank you for your great work !!





[DDC-168] serialization/unserialization of ClassMetadata lose reflFields order causing insertSql statement to fail Created: 20/Nov/09  Updated: 17/Dec/09  Resolved: 17/Dec/09

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA4
Fix Version/s: 2.0-ALPHA4
Security Level: All

Type: Bug Priority: Critical
Reporter: Eric Durand-Tremblay Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None


 Description   

This problem will be difficult to reproduce for you, but I isolated the exact cause of it.

To reproduce

  • Use any MetadataCache
  • Create a complex entity with some inheritance. (I may detail in later if your really need it)
  • Create an element of this entity with persist.
  • Create an other element of this entity but not on the same php run. (ex: reload the page)
  • The insert statement will fail because field names will not match parameters.

I narrowed it down to a serialization issue.

When you serialize an MetadataInfo, you don't serialize reflFields.
When you unserizlize you regenerate this value using ReflectionClass
That sound's like a good optimization.

The problem is that somehow, the reflection class can return the fields not in the same order that they were at the initial creation of the MetadataInfo.

Because the insertSql value is not re-generated, it can be out of sync with the new fields order.

The solution :
Call something like MetadataInfoFactory::_generateStaticSql (whish is private but ...) at wakeup time.



 Comments   
Comment by Roman S. Borschel [ 21/Nov/09 ]

Are you using composite keys anywhere?

The fact that reflFields is not serialized is not really an optimization but rather due to the fact that they simply can can not be serialized/unserialized properly.

We surely need some more concrete test case in order to reproduce this.

Comment by Eric Durand-Tremblay [ 23/Nov/09 ]

I do not uses composite key anyware.

The field who change place is a foreign key.

EntityRevision extends Entity
EntityRevision.parent_entity : manyToOne entity

(the field parent_entity_id changes place during serialization)

What do you need to reproduce the case ? Just entitiy classes? a completely fuctionnal project? some kind of unit test ?

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

Hm. the order shouldnt even matter because insertSql only contains placeholders. Can you show the SQL INSERT that is failing? With parameters, if possible, and error message.

Comment by Eric Durand-Tremblay [ 06/Dec/09 ]

For what I can remember, parameters are not bound in the right order which is causing an error like "field x could not be null"

INSERT INTO table (a, b) VALUES (?, ?)
bind : $b, $a

I will post the real query on monday morning when I get back to work.

Comment by Eric Durand-Tremblay [ 07/Dec/09 ]

Here is the real world example. I put the statement, the parameters, the error, and all the related entities.

INSERT INTO fna_client_revision (fna_parent_record_id, record_id, display_name, last_name, maiden_name, first_name, civility, gender, birthdate, employer, employment, employment_from, civil_status, civil_status_from, insurability, fna_client_fna_id, fna_spouse_fna_id, rev_no, created_at, modified_at, created_by, modified_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

Array
(
    [1] => 1
    [2] => George Simard2
    [3] => Simard2
    [4] =>
    [5] => George
    [6] =>
    [7] => MALE
    [8] => 1962-09-14
    [9] => Plomberie ABC Inc.
    [10] => Plombier
    [11] =>
    [12] => MARRIED
    [13] =>
    [14] => INSURABLE
    [15] => 5
    [16] => 2009-12-07 08:54:46
    [17] => 2009-12-07 08:54:46
    [18] =>  Eric Durand-Tremblay
    [19] =>  Eric Durand-Tremblay
    [20] => 1
    [21] =>
    [22] =>
)

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'employment' cannot be null
namespace ORM\BaseEntity;

/**
 * @MappedSuperclass
 */
class Entity
{
	private static $boolean_values = array("YES", 'NO');
	
	 /**
     * @Column(name="id", type="integer")
     * @Id
     * @GeneratedValue(strategy="AUTO")
     */
    protected $id;
    
    /**
     * @Column(name="created_at", type="datetime")
     */
    protected $created_at;
    
    /**
     * @Column(name="modified_at", type="datetime")
     */
    protected $modified_at;
    
    
     /**
     * @Column(name="created_by", type="string")
     */
    protected $created_by="";
    
    /**
     * @Column(name="modified_by", type="string")
     */
    protected $modified_by="";
}

/**
 * @MappedSuperclass
 * @HasLifecycleCallbacks
 */
class Revisionable extends ORM\BaseEntity\Entity
{

     /**
     * @Column(name="rev_no", type="integer")
     */
    protected $revision=1;
}


namespace ORM\BaseEntity;

/**
 * @MappedSuperclass
 * @HasLifecycleCallbacks
 */
class Client extends Revisionable
{

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

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

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

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

    /**
     * @Column(name="civility", type="string")
     */
    protected $civility="";
    
    /**
     * @Column(name="gender", type="string", length="25")
     */
    protected $gender="";

    /**
     * @Column(name="birthdate", type="date", nullable="true")
     */
    protected $birthdate;

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

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

    /**
     * @Column(name="employment_from", type="date", nullable="true")
     */
    protected $employment_from;

    /**
     * @Column(name="civil_status", type="string", length="25")
     */
    protected $civil_status="";
    
    /**
     * @Column(name="civil_status_from", type="date", nullable="true")
     */
    protected $civil_status_from;
    
    /**
     * @Column(name="insurability", type="string", length="25")
     */
    protected $insurability="";

    
    /**
     * @OneToOne(targetEntity="ORM\Entity\FNA")
     * @JoinColumns({
     *   @JoinColumn(name="fna_client_fna_id", referencedColumnName="id")
     * })
     */
    protected $client_fna;

	/**
     * @OneToOne(targetEntity="ORM\Entity\FNA")
     * @JoinColumns({
     *   @JoinColumn(name="fna_spouse_fna_id", referencedColumnName="id")
     * })
     */
    protected $spouse_fna;
}


namespace ORM\RevisionEntity;

/**
 * @Entity
 * @Table(name="fna_client_revision", indexes={@index(name="idx_record_id", columns={"record_id"})})
 * @HasLifecycleCallbacks
 */
class Client extends ORM\BaseEntity\Client{
	
	 /**
     * @ManyToOne(targetEntity="Kronos\FNA\ORM\Entity\Client")
     * @JoinColumns({
     *   @JoinColumn(name="fna_parent_record_id", referencedColumnName="id", onDelete="SET NULL")
     * })
     */
    protected $parent_record;  /// HERE IS THE  FIELD WHO CHANGE PLACE AFTER SERIALIZATION !!!!!!!!!!!!!!!!!!!!!!
    
    /**
     * 
     * @Column(name="record_id", type="int")
     */
    protected $record_id;
}

Comment by Eric Durand-Tremblay [ 07/Dec/09 ]
   
    [1] => 1  (fna_parent_record_id)
(expected record_id)
    [2] => George Simard2 (display_name)
    [3] => Simard2 (last_name)
    [4] => (maiden_name)
    [5] => George (first_name)
    [6] => (civility)
    [7] => MALE (gender)
    [8] => 1962-09-14 (birthdate)
    [9] => Plomberie ABC Inc. (employer)
    [10] => Plombier (employment)
    [11] => (employment_from)
    [12] => MARRIED (civil_status)
    [13] => (civil_status_from)
    [14] => INSURABLE (insurability)
    [15] => 5 (rev_no)
    [16] => 2009-12-07 08:54:46 (created_at)
    [17] => 2009-12-07 08:54:46 (modified_at)
    [18] =>  Eric Durand-Tremblay (created_by)
    [19] =>  Eric Durand-Tremblay (modified_by)
    [20] => 1 (record_id) !! Should be in position  2
    [21] => (fna_client_fna_id)
    [22] => (fna_spouse_fna_id)

Comment by Benjamin Eberlei [ 07/Dec/09 ]

I could reproduce the issue and generated a failing test for this. We already discussed how this might be fixed.

Comment by Eric Durand-Tremblay [ 07/Dec/09 ]

This is a very good news !

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

Should be fixed now.

Comment by Eric Durand-Tremblay [ 17/Dec/09 ]

Resolution confirmed.

Thank your for your great work !





[DDC-164] find() not polymoprhic with single table inheritance Created: 20/Nov/09  Updated: 21/Nov/09  Resolved: 21/Nov/09

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA3
Fix Version/s: 2.0-ALPHA4
Security Level: All

Type: Bug Priority: Critical
Reporter: Roman S. Borschel Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None





[DDC-152] Polymorphic queries and fields of subclasses Created: 16/Nov/09  Updated: 19/Dec/09  Resolved: 19/Dec/09

Status: Closed
Project: Doctrine 2 - ORM
Component/s: DQL, ORM
Affects Version/s: 2.0-ALPHA3
Fix Version/s: 2.0-ALPHA4
Security Level: All

Type: Bug Priority: Critical
Reporter: Roman S. Borschel Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None


 Description   

Currently fields of subclasses are added to the ResultSetMapping under the alias of the queried (parent) class. Later during hydration if the queried (parent) class does not own a field AbstractHydrator#_lookupDeclaringClass looks up the first subclass that defines a field with that name. However, multiple subclasses can define a field with the same name, so this is error-prone.

Fields of subclasses in a polymorphic query should probably be added to the ResultSetMapping with their own alias. The lookup during hydration should be removed and the information which field belongs to which class encoded in the ResultSetMapping.






[DDC-145] Cascaded delete on a lazyloaded persistent collection Created: 13/Nov/09  Updated: 13/Nov/09  Resolved: 13/Nov/09

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA3
Fix Version/s: 2.0-ALPHA4
Security Level: All

Type: Bug Priority: Critical
Reporter: Avi Block Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None


 Description   

It seems that if you call PersistentCollection#unwrap on a lazy loaded collection, you get nothing back (unless you initialize the collection first). Because of this, UnitOfWork#_cascadeRemove is "unwrapping" the collection before transversing it, and nothing gets deleted on the cascade.



 Comments   
Comment by Roman S. Borschel [ 13/Nov/09 ]

Right, I think I made that change for all _cascade* methods but actually I think for _cascadeRemove initialization is actually intended. For the others it doesnt make sense.

Comment by Roman S. Borschel [ 13/Nov/09 ]

Will need to write a functional test for this before I fix it by reverting the change for _cascadeRemove.





[DDC-141] DQL with WHERE queries on Single Table Inheritance Entities fail Created: 13/Nov/09  Updated: 13/Nov/09  Resolved: 13/Nov/09

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA3
Fix Version/s: 2.0-ALPHA4
Security Level: All

Type: Bug Priority: Critical
Reporter: Nico Kaiser Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None


 Description   

The ORM query builder seems to be broken for Single Table Inheritance with discriminator.

When using inheritance like here:
http://www.doctrine-project.org/documentation/manual/2_0/en/inheritance-mapping#single-table-inheritance

Queries with WHERE fail:

SELECT p FROM MyProject\Model\Person p WHERE p.id = 1

This translates to this SQL:

SELECT p0_.id AS id0, p0_.discr AS discr1 FROM person p0_ WHERE p0_.id = 1 p0_.discr IN ('', 'person', 'employee')

(AND is missing after p0_.id = 1)



 Comments   
Comment by Roman S. Borschel [ 13/Nov/09 ]

Thanks for reporting this. I'm just wondering where the empty string in the IN clause comes from? I dont seem to be able to reproduce that bit.

Comment by Nico Kaiser [ 13/Nov/09 ]

Argh, ignore the empty string, it is

SELECT p0_.id AS id0, p0_.discr AS discr1 FROM person p0_ WHERE p0_.id = 1 p0_.discr IN ('person', 'employee')

My initial example was a superclass that did not appear in the DiscriminatorMap...

Comment by Roman S. Borschel [ 13/Nov/09 ]

OK. Should be fixed now. Was a very trivial mistake. Now its covered in the tests.





[DDC-137] Only last relation id updated with multiple one-to-one self-referencing relations Created: 12/Nov/09  Updated: 15/Nov/09  Resolved: 15/Nov/09

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA3
Fix Version/s: 2.0-ALPHA4
Security Level: All

Type: Bug Priority: Critical
Reporter: Reinier Kip Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None


 Description   

Take this simplified situation:

/** @Entity */
class Entity {
	/** @Id @GeneratedValue(strategy="AUTO") @Column(type="integer") */
	public $id;

	/**
	 * @OneToOne(targetEntity="Entity", cascade={"persist"})
	 * @JoinColumn(name="other1", referencedColumnName="id")
	 */
	public $other1;

	/**
	 * @OneToOne(targetEntity="Entity", cascade={"persist"})
	 * @JoinColumn(name="other2", referencedColumnName="id")
	 */
	public $other2;
}

$entity1 = new Entity();
$em->persist($entity1);
$entity1->other1 = $entity2 = new Entity();
$entity1->other2 = $entity3 = new Entity();
$em->flush();

The entities' ids are now:

Entity 1: 1, Entity 2: 2, Entity 3: 3

However, the other1's relation id is not updated:

id	other1	other2
1  	NULL 	3:	// other1's id is missing
2 	NULL 	NULL
3 	NULL 	NULL

The SQL clarifies:

INSERT INTO Entity (other1, other2) VALUES (?, ?)
array(2) {
  [1]=>
  NULL
  [2]=>
  NULL
}
INSERT INTO Entity (other1, other2) VALUES (?, ?)
array(2) {
  [1]=>
  NULL
  [2]=>
  NULL
}
INSERT INTO Entity (other1, other2) VALUES (?, ?)
array(2) {
  [1]=>
  NULL
  [2]=>
  NULL
}
UPDATE Entity SET other2 = ? WHERE id = ?
array(2) {
  [0]=>
  int(3)
  [1]=>
  int(1)
}

Adding 'other3' proved that only the last relation id is updated, as such:

id	other1	other2	other3
1  	NULL 	NULL	4	// other1 and other2 missing
2 	NULL 	NULL	NULL
3 	NULL 	NULL	NULL
4 	NULL 	NULL	NULL

This is not the case with relations that reference to entities outside the class hierarchy (so the same problem occurs with relations inside the class hierarchy).



 Comments   
Comment by Roman S. Borschel [ 15/Nov/09 ]

Thanks, should be fixed now.





[DDC-132] Subclass' columns missing from cached ClassMetadata::$resultColumnNames Created: 09/Nov/09  Updated: 09/Dec/09  Resolved: 09/Dec/09

Status: Closed
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers, ORM
Affects Version/s: 2.0-ALPHA3
Fix Version/s: 2.0-ALPHA4
Security Level: All

Type: Bug Priority: Critical
Reporter: Reinier Kip Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None

Attachments: File patch.diff    

 Description   

I have a Customer with class table inheritance mapping and some fields, and a subclass called SuperCustomer with two fields: bool `isSuper` and string `extra`.

I found that when replacing the usual ArrayCache with a MemcacheCache, everything works fine on the first request, but notices occur on subsequent requests:

Notice: Undefined index: isSuper in X:\...\Doctrine\ORM\Persisters\StandardEntityPersister.php on line 577
Notice: Undefined index: extra in X:\...\Doctrine\ORM\Persisters\StandardEntityPersister.php on line 577

Inspection of ClassMetadata::$resultColumnNames on line 569 showed that the two fields `isSuper` and `extra` were (the only things) missing. The resulting object's `isSuper` and `extra` properties were empty.

I have yet to find the cause of this, but maybe you have an idea.



 Comments   
Comment by Roman S. Borschel [ 09/Nov/09 ]

This is indeed strange. My first guess was that the resultColumnNames get lost during serialization but the ClassMetadata#__sleep implementation seems to be correct in so far as it returns the resultColumnNames field as part of the fields to serialize.

Let me know as soon as you have more information.

Btw. Which metadata driver are you using? Annotations?

Comment by Reinier Kip [ 10/Nov/09 ]

> My first guess was that the resultColumnNames get lost during serialization
This would be really strange, as the columns of the parent class Customer are still there after unserialization, so only a part is lost during serialization. My first guess was that the metadata is cached before the metadata loading is finished.

> Which metadata driver are you using? Annotations?
I'm using a custom metadata driver. Caching is separated from the driver, so the driver couldn't have anything to do with this, right?

I'll try to find where it goes wrong and let you know.

Comment by Reinier Kip [ 10/Nov/09 ]

First request:

  • Customer metadata is loaded and cached to Customer$CLASSMETADATA. $resultColumnNames contains Customer's fields.
  • SuperCustomer metadata is loaded and cached to SuperCustomer$CLASSMETADATA. $resultColumnNames contains Customer's and SuperCustomer's fields.
  • I request an object of class Customer be loaded from the database, which is an instance of SuperCustomer.
  • StandardEntityPersister::_createEntity() is called to create the entity, and uses Customer metadata ALSO CONTAINING SuperCustomer's $resultColumnNames.

Second request:

  • Customer metadata is loaded from Customer$CLASSMETADATA. $resultColumnNames contains Customer's fields.
  • SuperCustomer metadata is loaded from SuperCustomer$CLASSMETADATA. $resultColumnNames contains Customer's and SuperCustomer's fields.
  • I request an object of class Customer be loaded from the database, which is an instance of SuperCustomer.
  • StandardEntityPersister::_createEntity() is called to create the entity, and uses Customer metadata NOT CONTAINING SuperCustomer's $resultColumnNames.

Thought: the Customer's metadata is somehow changed after caching to cope with Customer's subclasses as well, but these changes are not in the cache. I don't have enough knowledge of Doctrine's internals, but you probably have a pretty good idea where this could happen.

Comment by Roman S. Borschel [ 10/Nov/09 ]

Thanks for your detailed information. I think I know what the issue is now. May be non-trivial to fix. I will try to look into it as soon as I got some free time.

Comment by Jonathan H. Wage [ 11/Nov/09 ]

Here is a patch which fixes the issue but through doing this roman and I realized another issue.

Comment by Roman S. Borschel [ 11/Nov/09 ]

Scheduled for ALPHA4 as this may need some restructuring.

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

This should be fixed now in trunk.





[DDC-119] Collection change tracking broken with NOTIFY policy Created: 06/Nov/09  Updated: 16/Jul/10  Resolved: 15/Jul/10

Status: Closed
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: 2.0-ALPHA2
Fix Version/s: 2.0-BETA3
Security Level: All

Type: Bug Priority: Critical
Reporter: Roman S. Borschel Assignee: Roman S. Borschel
Resolution: Fixed Votes: 1
Labels: None


 Description   

Looks like change tracking of collections together with the NOTIFY policy doesnt work well as collection updates are detected in _computeAssociationChanges. Perhaps the collection itself should inform the UnitOfWork directly?



 Comments   
Comment by Kawsar Saiyeed [ 16/Mar/10 ]

Not sure if the issue is identical but seems at least related. Using NOTIFY change tracking with many-to-many bidirectional associations does not work. Objects added to the associations do not get persisted when calling EntityManager#flush.

Tested on r7404.

Comment by Michael Zach [ 16/Jul/10 ]

Dear Roman,

the line # 456 in UnitOfWork.php seems wrong to me:

            $isChangeTrackingNotify = isset($this->entityChangeSets[$oid]);

Shouldn't this only be set if the entity has

 @ChangeTrackingPolicy("NOTIFY") *

set in his class docBlock? The current behaviour now is to assign $changeset if changes exists, leaving the NOTIFY tracking policy out:

             $changeSet = $isChangeTrackingNotify ? $this->entityChangeSets[$oid] : array();

Because of this change, all our unit tests involving saving of entites break (basically, the whole application), which implement @postUpdate for logging purposes logging an own computed changeset.

Comment by Roman S. Borschel [ 16/Jul/10 ]

Hi,

you're right, I did that naivly because I thought the only case where an entity would already have a changeset on flush is with the NOTIFY policy. I did not think of custom use cases like yours. It is fixed now in master. My apologies. However, this still means your approach would be broken if you would use the NOTIFY policy right? That sounds like maybe there is potential to improve the approach you're currently using. If you're missing anything in the API or implementation that forbids a different approach feel free to raise some new JIRA issues so we can possibly improve the situation.

Comment by Michael Zach [ 16/Jul/10 ]

Thank you for fixing this real quick! Our current approach is to compute the changeset on @preUpdate and after a successful save write the changeset to the database in @postUpdate. This conflicted with the changes made, I will however look into it and see if it's feasible for us to implement another approach.

Once again, thanks for your reply and fix.





[DDC-116] array_combine error when using combined Primary Key Created: 05/Nov/09  Updated: 14/Jun/10  Resolved: 06/Nov/09

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

Type: Bug Priority: Critical
Reporter: Nico Kaiser Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None

Attachments: Text File Assigned.php    

 Description   

I use a combined Primary Key for a User's Phonenumber entity (to match our existing DB model). The key is combined from a "Type" field and a "userId" field that references the User table.

To mark the (referenced!) userId field and the type field as PK, I need to add "userId" to the model (adding @Id to User does not work). This works well when generating Users and Phonenumbers - but the delete command breaks:

PHP Warning: array_combine(): Both parameters should have an equal number of elements in ..../lib/Doctrine/ORM/Persisters/StandardEntityPersister.php on line 274
PHP Catchable fatal error: Argument 2 passed to Doctrine\DBAL\Connection::delete() must be an array, boolean given, called in ..../lib/Doctrine/ORM/Persisters/StandardEntityPersister.php on line 275 and defined in ..../lib/Doctrine/DBAL/Connection.php on line 372

Entities:
http://pastebin.com/d51e021e2

Test code:
http://pastebin.com/m51d1f497



 Comments   
Comment by Nico Kaiser [ 06/Nov/09 ]

I attached a patch for Doctrine\Orm\Id\Assigned, there seems to be a runaway line which makes the class add each element twice...

Comment by Roman S. Borschel [ 06/Nov/09 ]

Whoops. Thanks for finding this! Does it fix this issue? I will need to add a testcase to the suite.

Comment by Nico Kaiser [ 06/Nov/09 ]

Does not entirely fix it: if the $value is empty, too few elements are added again.
Need to remove the "if (isset($value)) {" clause. I'll attach the fixed Assigned.php.

Comment by Roman S. Borschel [ 06/Nov/09 ]

I think the isset() is correct. That way the $identifier array remains empty if the PK is null and later if ( ! $identifier) evaluates to false on the empty array and raises the exception. If we remove the isset() we would "accept" PKs with null values. But it might be better to do:

 if (!isset($value)) {
        throw ORMException::entityMissingAssignedId($entity);
  } else {
         $identifier[] = $value;
 }
Comment by Roman S. Borschel [ 06/Nov/09 ]

I will fix this and add some new tests for it.

Comment by Roman S. Borschel [ 06/Nov/09 ]

Should be fixed now.





[DDC-113] Cascaded persist avoids LifecycleCallbacks Created: 04/Nov/09  Updated: 18/Dec/09  Resolved: 18/Dec/09

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA3
Fix Version/s: 2.0-ALPHA4
Security Level: All

Type: Bug Priority: Critical
Reporter: Nico Kaiser Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None


 Description   

When an Entity is created by 'cascade=

{"persist"}

', its LifecycleCallbacks (e.g. "PrePersist"!) are not invoked.

When it is persisted explicitly, everything workes fine and the events are called...



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

Works for me on trunk, added test-case that proves it (Doctrine\Tests\ORM\Functional\LifecycleCallbackTest::testCascadedEntitiesCallsPrePersist())

Comment by Nico Kaiser [ 14/Dec/09 ]

There is still an issue. You can reproduce it if you change the test case slightly to this:

    /**
     * @group DDC-113
     */
    public function testCascadedEntitiesCallsPrePersist()
    {
        $e1 = new LifecycleCallbackTestEntity;
        $e2 = new LifecycleCallbackTestEntity;

        $c = new LifecycleCallbackCascader();
        
        $this->_em->persist($c);
        
        $c->entities[] = $e1;
        $c->entities[] = $e2;

        //$this->_em->persist($c);
        $this->_em->flush();

        $this->assertTrue($e1->prePersistCallbackInvoked);
        $this->assertTrue($e2->prePersistCallbackInvoked);
    }

The difference to the existing (and indeed working) test case is that the Cascader entity is persisted before the collection entries are added.

Comment by Benjamin Eberlei [ 14/Dec/09 ]

That is valid behaviour according to the lifecycle of an entity, persist gets cascaded right and only when ->persist() is called.

In the case you show, the two entities are also not persisted, because the cascade was already executed.

Comment by Nico Kaiser [ 14/Dec/09 ]

From a technical point of view this is ok - but from an intuitive point of view I would think I can use persist whereever I want. So I can create an entity, persist it (so it gets written to the DB), make changes to it (like adding entities to its collection) and getting its saved (and the collection entities persisted) when I call flush().

So I suspect lifecycle events to be called whenever an entity is persisted. And in this case LifecycleCallbackTestEntity's are persisted automatically by flush() (and this is after the Cascader is persisted!), so lifecycle events should fire here.

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

I have a fix for this ready, however, I want to look into something else before committing. I'll address this over the weekend.

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

Should be fixed now.





[DDC-61] OneToOne relation with an entity using Class Table Inheritance fails Created: 27/Oct/09  Updated: 04/Nov/09  Resolved: 03/Nov/09

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

Type: Bug Priority: Critical
Reporter: Ville Väänänen Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None

Attachments: File cti_test.diff     File cti_test.diff     File StandardEntityPersister.php.diff    

 Description   

The bug occurs when there's a lazy bidirectional one-to-one relation where the inverse side only specifies the root entity. In this case, the final type of the target-entity is not resolved correctly. See the attached file for a failing test case.



 Comments   
Comment by Ville Väänänen [ 27/Oct/09 ]

The situation is actually worse if the relation is eager. In that case not only is the classname incorrectly resolved, but if the root-entity is an abstract class, the execution ends up in a fatal error.

It would seem to me that there are two ways to deal with the described problem:

1. join all the tables that contain the discriminator-fields, so that the correct subclasses can be inferred
OR
2. change the proxy pattern to a variant which is used in the FLOW3 framework, where there's only one proxy-class

Comment by Ville Väänänen [ 27/Oct/09 ]

A fix to the patch. Use the newer attachment.

Comment by Ville Väänänen [ 02/Nov/09 ]

I have patches for both of the options above. Should this be a configuration option? As it stands now, OneToMany and ManyToMany relationships enjoy the advantage of having the Collection in between the target and source entities. We could even use a hybrid approach, where a general proxy-object is created only when the object type cannot be inferred without joins.

Comment by Roman S. Borschel [ 02/Nov/09 ]

It should of course be Nr. 1. The discriminator column is always stored in the topmost (root) table and tables of base classes must be joined, always. If this is not the case this is a bug. Can you show your patch?

Comment by Ville Väänänen [ 03/Nov/09 ]

It would seem to me that this would cause an inconsistency in how similar associations with different kinds of entities are treated.

From DDC-38: But inverse sides of one-one associations can never be lazy. Now going with option 1 would mean that in case the association is with an entity using class-table inheritance, these lazy associations would be allowed (because if we're joining the base-table anyway, there's no reason to forbid this) . This begs the question that if we're ready to do the joins in this case, should we reconsider doing them also to find out about target-existency when dealing with other types of entities?

Comment by Ville Väänänen [ 03/Nov/09 ]

Describing the changes StandardEntityPersister.php.diff:

  • _getSelectEntitiesSql
    • For every inverse OneToOne relation join the target-table/base-table and find out the existence of the target-entity and the value of the discriminator column if one should exist. These values are given the names of the sourceFieldNames in the result array
  • _createEntity
    • Pass the existence and discrimnator column values to unitOfWork->createEntity in the hints['associations'] array. This part is only speculative.

This selects the existence/discrimator-column information when an entity is queried using EntityManager->find, it's doesn't help if one is using a DQL query.

Comment by Roman S. Borschel [ 03/Nov/09 ]

I understand now what the problem is. Its tricky. Your testcase however has a wrong mapping. The way you mapped it, any event that is fetched of a company will automatically be the main event In this case it would be correct to put a join column on the organization (main_event_id). But I understand the problem and will create a separate new test for it.

It will probably be treated similar to inverse sides of one-one. That means, when a one-one associations references a target entity that is a base type (not an outermost type, that means there are still possible subtypes), whether the association is the owning side or not it must be eagerly fetched.

Comment by Ville Väänänen [ 04/Nov/09 ]

Okay, so not allowing lazy-loading in this case at all. Why is this? As I stated earlier there are at least to ways to solve this without resorting to eager-loading. If using class-table inheritance means forgetting about lazy-load, to me at least it's a huge disadvantage and would be a deal breaker in using this inheritance-type. The problem with eager-load is not the first fetch that follows, but the uncertainty of how many fetches are going to follow in total. If the target-entity is the tip of a huge object-hierarchy full of entities using class-table inheritance, the current strategy is unusable. Having a couple of extra tables joined is nothing compared to the snowball that eager-fetching might get rolling.

Comment by Roman S. Borschel [ 04/Nov/09 ]

Well, option Nr.1 is too complicated and can lead to lots of new issues. You can not always join arbitrary tables, not when it comes to DQL where it alters the overall result. The situation is much more complex than it might look to you right now.

Nr.2 is no option at all because such a proxy approach does not even hold for instanceof checks. An absolute no-go.

What it does now is the best thing from my point of view. If performance becomes an issue you can always improve upon that by eager fetching with DQL. Also, you did not yet understand how it works. The eager load does not happen always with class table inheritance, only when the target entity is a base type. If it is a subtype that does not have any further subtypes, then a proxy can be used without fear. Same goes for single table inheritance.

Comment by Roman S. Borschel [ 04/Nov/09 ]

If you still feel this is too bad open a new issue as "improvement" and move any old/new patches you have there. There would need to be much more tests for such a change. Also you did not mention whether your patch actually passes all existing unit tests.

Comment by Ville Väänänen [ 04/Nov/09 ]

Sure I understood how it works. But to me one of the biggest advantages of class-table inheritance is exactly that the parent doesn't have to know the final type., and so in the configuration the association is pointed to the base-type. Yes, I accept that the issue might be way too complicated in the DQL case.

Option number two can be improved if the parent model that might have these general proxies invokes a load in it's getters. Exactly the way the generated proxies work now. Of course, this means that the models need to be aware of the possible proxies. It's not perfect, but maybe it could be an option?

Comment by Roman S. Borschel [ 04/Nov/09 ]

Please open a new issue, I think this has potential as an improvement that can complement the current behavior.

What I mean is: for normal find/load ... operations that are not triggered by DQL we can probably do the join and in the case of DQL the current behavior is used, if you want to avoid the extra query in that case its as simple as adding the join to DQL.

So I think the approaches can be complementary.

Comment by Ville Väänänen [ 04/Nov/09 ]

Sure like the sound of that! I will be very happy to open this as an improvement. Thanks for your patience .





[DDC-74] Updates get lost when Lifecycle Events (@PreUpdate) are invoked Created: 29/Oct/09  Updated: 13/Nov/09  Resolved: 13/Nov/09

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

Type: Bug Priority: Critical
Reporter: Nico Kaiser Assignee: Roman S. Borschel
Resolution: Fixed Votes: 1
Labels: None


 Description   

When Lifecycle Events are invoked on entity update (@PreUpdate), the entity is not updated properly in the database.

This code creates a User object, sets its name to "Bob" and its value to empty, then updates the object and updates the name to "Alice".

$user = new User;
$user->setName('Bob');
$user->setValue('');
$em->persist($user);
$em->flush();
$user->setName('Alice');
$em->flush();

However, when the User class has a @PreUpdate event that e.g. sets the value to "Hello World", the name change gets lost and only the value is updated by the second flush() call.

This is a critical bug which prevents creation of entities that simulate the "Timestampable" behaviour of Doctrine 1.x...



 Comments   
Comment by Benjamin Eberlei [ 02/Nov/09 ]

I think this might be a hen-egg problem.

@PreUpdate is only invoked after it is calculated that a change occured on all those entities that have updates. After a change in @PreUpdate events there would have to be another calculation of changes on all those entities, which would probably mean a significant performance hit.

Comment by Eric Durand-Tremblay [ 13/Nov/09 ]

I may not know all the consequences of this, but I think I have a fix for this bug.

In the class ORM\UnitOfWork

As I understand it, computeSingleEntityChangeSet() is called to update the changeset and _originalEntityData is set to the current values.

But, I see that the old changes are lost.

If i modify the function computeSingleEntityChangeSet to merge the changeset, it works.

At line 656 replace

$this->_entityChangeSets[$oid] = $changeSet;

By :

if($this->_entityChangeSets[$oid]){
    $this->_entityChangeSets[$oid] += $changeSet;
}
else {
    $this->_entityChangeSets[$oid] = $changeSet;
}

Here is my test case :

$qb = new \Doctrine\ORM\QueryBuilder($em);
$qb->select('fna')
			->from('Entity\FNA', 'fna')
			->andwhere($qb->expr()->eq('fna.id', ':fna_id'));
$qb->setParameter('fna_id', 1);
$query = $qb->getQuery();

$fna = $query->getSingleResult();
		
$fna->setStatus('COMPLETED');
$em->persist($fna);
$em->flush();

AND The preUdate :

/** 
 * @PreUpdate
*/
public function onPreUpdate($args=false)
 {
        $this->modified_at = new \DateTime();
}
Comment by Roman S. Borschel [ 13/Nov/09 ]

Indeed this looks like a good fix except that the addition has to be the other way around so that when the same field is changed twice, first before the flush and then in a lifecycle callback/event the change from the callback prevails.

I will work on this and write a test for it.

Thanks Eric.

Comment by Roman S. Borschel [ 13/Nov/09 ]

Fixed now.

Thanks Nico for reporting and thanks Eric for the suggestion!





[DDC-41] Getting error with lazy loading via createQuery() followed by $em->flush() Created: 10/Oct/09  Updated: 12/Oct/09  Resolved: 12/Oct/09

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

Type: Bug Priority: Critical
Reporter: Nichlas Löfdahl Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None
Environment:

Doctrine2-trunk, Postgresql, Lazy loading



 Description   

Simple O-O relationship between \Entities\User and \Entities\Feed. Seems like there's a problem with not-yet lazy-loaded proxies and $em->flush().

"Entities/User.php"
<?php
namespace Entities;

/** @Entity @Table(name="users_debug") */
class User {
    /**
     * @Id @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @OneToOne(targetEntity="Feed", mappedBy="User", cascade={"persist"})
     */
    private $Feed;

    public function getID() {
        return $this->id;
    }
    public function getFeed() {
        return $this->Feed;
    }
    public function setFeed($feed) {
        $this->Feed = $feed;
    }
}
?>
"Entities/Feed.php"
<?php
namespace Entities;

/**
 * @Entity @Table(name="feeds_debug")
 */
class Feed {
    /**
     * @Id @Column(type="integer")
     * @GeneratedValue(strategy="AUTO", allocationSize=1)
     */
    private $id;

     /**
     * @OneToOne(targetEntity="User", cascade={"persist"})
     * @JoinColumn(name="user_id", referencedColumnName="id")
     */
    private $User;

    function setID($value) {
        $this->id = $value;
    }
    function getID() {
        return $this->id;
    }
    function getUser() {
        return $this->User;
    }
    function setUser($user) {
        $this->User = $user;
    }
}


?>

Table-data

users_debug:
 id
 361

feeds_debug:
 id  | user_id
 461 |     361

Code:

$user = $em->createQuery("SELECT u FROM Entities\User u WHERE u.id = 361")->getSingleResult();
print $user->getID(); // 361
// uncomment line below and it works
// print $user->getFeed()->getID();
$em->flush();

Error:
Warning: spl_object_hash() expects parameter 1 to be object, null given in /home/crotalus/src/Doctrine2-Dev/lib/Doctrine/ORM/UnitOfWork.php on line 1010
Warning: spl_object_hash() expects parameter 1 to be object, null given in /home/crotalus/src/Doctrine2-Dev/lib/Doctrine/ORM/UnitOfWork.php on line 566
Warning: ReflectionProperty::setValue() expects parameter 1 to be object, null given in /home/crotalus/src/Doctrine2-Dev/lib/Doctrine/ORM/UnitOfWork.php on line 575
Warning: get_class() expects parameter 1 to be object, null given in /home/crotalus/src/Doctrine2-Dev/lib/Doctrine/ORM/UnitOfWork.php on line 979
Fatal error: Uncaught exception 'ReflectionException' with message 'Class does not exist' in /home/crotalus/src/Doctrine2-Dev/lib/Doctrine/ORM/Mapping/ClassMetadata.php:69
Stack trace:
#0 /home/crotalus/src/Doctrine2-Dev/lib/Doctrine/ORM/Mapping/ClassMetadata.php(69): ReflectionClass->__construct(false)
#1 /home/crotalus/src/Doctrine2-Dev/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php(247): Doctrine\ORM\Mapping\ClassMetadata->__construct(false)
#2 /home/crotalus/src/Doctrine2-Dev/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php(177): Doctrine\ORM\Mapping\ClassMetadataFactory->_newClassMetadataInstance(false)
#3 /home/crotalus/src/Doctrine2-Dev/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php(115): Doctrine\ORM\Mapping\ClassMetadataFactory->_loadMetadata(false)
#4 /home/crotalus/src/Doctrine2-Dev/lib/Doctrine/ORM/EntityManager.php(212): Doctrine\ORM\Mapping\ClassMetadataFactory->getMetadataFor(false)
#5 /home/crotalus/src/Doctrine2-Dev/lib/Doctrine/ORM/UnitOfWork.php(979): Doctrine\ORM\EntityManager->getClassMetadata in /home/crotalus/src/Doctrine2-Dev/lib/Doctrine/ORM/Mapping/ClassMetadata.php on line 69

PostgreSQL log:
2009-10-10 16:32:58 CEST LOGG: execute pdo_stmt_000000000a283af8: SELECT u0_.id AS id0 FROM users_debug u0_ WHERE u0_.id = 361
2009-10-10 16:32:58 CEST LOGG: sats: DEALLOCATE pdo_stmt_000000000a283af8
2009-10-10 16:32:58 CEST LOGG: execute pdo_stmt_000000000a283af8: SELECT NEXTVAL('feeds_debug_id_seq')
2009-10-10 16:32:58 CEST LOGG: sats: DEALLOCATE pdo_stmt_000000000a283af8
2009-10-10 16:32:58 CEST LOGG: execute pdo_stmt_000000000a283af8: SELECT NEXTVAL('users_debug_id_seq')
2009-10-10 16:32:58 CEST LOGG: sats: DEALLOCATE pdo_stmt_000000000a283af8



 Comments   
Comment by Roman S. Borschel [ 12/Oct/09 ]

Strange, all the warnings and errors and the stack trace rather indicate that the associated value is NULL and not a (not initialized) proxy object. I'm working on this and already found an issue to address but I'm still unable to exactly reproduce this. Will keep you updated. If you have any further information, please let me know.

Comment by Roman S. Borschel [ 12/Oct/09 ]

OK, managed to reproduce this. Working on it.

Comment by Roman S. Borschel [ 12/Oct/09 ]

This should now be fixed but you need to manually delete your proxy classes so that they're regenerated. More improvements to the proxy classes and CLI tasks for (re)generating proxy classes will follow.





[DDC-34] schema-tool --create tries to create duplicate associations and exits with exception Created: 07/Oct/09  Updated: 07/Oct/09  Resolved: 07/Oct/09

Status: Closed
Project: Doctrine 2 - ORM
Component/s: Tools
Affects Version/s: 2.0-ALPHA2
Fix Version/s: 2.0-ALPHA3
Security Level: All

Type: Bug Priority: Critical
Reporter: Ismo Toijala Assignee: Jonathan H. Wage
Resolution: Fixed Votes: 0
Labels: None
Environment:

HEAD



 Description   

I'm getting the error

SchemaTool:Duplicate field mapping ()

when trying to create my database schema. I am pretty sure this worked before. The error occurs on a field defined in a mapped superclass on the first entity that extends this class on the first association.

My entity classes:

namespace Model;

use \Model\User\User;
use \DateTime;

/**
 * @MappedSuperclass
 */
abstract class Blameable
{
	/**
	 *
	 * @var DateTime
	 *
	 * @Column(type="datetime", name="date_created")
	 */
	protected $dateCreated;

	/**
	 *
	 * @var User
	 *
	 * @OneToOne(targetEntity="Model\User\User")
     * @JoinColumn(name="creator_id", referencedColumnName="id", nullable="true")
	 */
	protected $creator;

	/**
	 *
	 * @var DateTime
	 *
	 * @Column(type="datetime", name="date_updated", nullable="true")
	 */
	protected $dateUpdated;

	/**
	 *
	 * @var User
	 *
	 * @OneToOne(targetEntity="Model\User\User")
     * @JoinColumn(name="updater_id", referencedColumnName="id", nullable="true")
	 */
	protected $updater;

	/**
	 *
	 * @var DateTime
	 *
	 * @Column(type="datetime", name="date_deleted", nullable="true")
	 */
	protected $dateDeleted;

	/**
	 *
	 * @var User
	 *
	 * @OneToOne(targetEntity="Model\User\User")
     * @JoinColumn(name="deleter_id", referencedColumnName="id", nullable="true")
	 */
	protected $deleter;
}
namespace Model\User;

use \Zend_Validate_Alnum;
use \Zend_Validate_StringLength;
use \Zend_Validate_Alpha;
use \Zend_Validate_EmailAddress;
use \Zend_Registry;
use \Model\Blameable;
use \Model\ConstraintException;
use \Itoijala_Singletons;
use \Zend_Auth;
use \Itoijala_Password_Hash;

/**
 *
 *
 * @Entity @Table(name="user_users")
 */
class User extends Blameable
{
	/**
	 *
	 * @var int
	 *
	 * @Id @Column(type="integer", name="id")
     * @GeneratedValue(strategy="AUTO")
	 */
	private $id;

	/**
	 *
	 * @var string
	 *
	 * @Column(type="string", length="20", name="username")
	 */
	private $username;

	/**
	 *
	 * @var string
	 *
	 * @Column(type="string", length="20", name="first_name")
	 */
	private $firstName;

	/**
	 *
	 * @var string
	 *
	 * @Column(type="string", length="20", name="last_name")
	 */
	private $lastName;

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

	/**
	 *
	 * @var string
	 *
	 * @Column(type="string", length="20", name="signature")
	 */
	private $signature;

	/**
	 *
	 * @var string
	 *
	 * @Column(type="string", length="128", name="password")
	 */
	private $password;

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

	/**
	 *
	 * @var string
	 *
	 * @Column(type="string", length="32", name="session_id", nullable="true")
	 */
	private $sessionId;

	/**
	 *
	 * @var bool
	 *
	 * @Column(type="boolean", name="unlocked")
	 */
	private $unlocked;
}
namespace Model\Article;

use \Closure;
use \Model\Blameable;
use \Doctrine\Common\Collections\Collection;
use \Doctrine\ommon\Collections\ArrayCollection;
use \Model\User\User;
use \Model\Gallery\Gallery;
use \Model\ConstraintException;
use \Zend_Validate_StringLength;

/**
 * @Entity @Table(name="article_articles")
 */
class Article extends Blameable
{
	/**
	 *
	 * @var int
	 *
	 * @Id @Column(type="integer", name="id")
     * @GeneratedValue(strategy="AUTO")
	 */
	private $id;

	/**
	 *
	 * @var Category
	 *
	 * @ManyToOne(targetEntity="Model\Article\Category")
     * @JoinColumn(name="category_id", referencedColumnName="id")
	 */
	private $category;

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

	/**
	 *
	 * @var string
	 *
	 * @Column(type="text", name="description")
	 */
	private $description;

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

	/**
	 *
	 * @var string
	 *
	 * @Column(type="text", name="content")
	 */
	private $content;

	/**
	 *
	 * @var int
	 *
	 * @Column(type="integer", name="views")
	 */
	private $views;

	/**
	 *
	 * @var bool
	 *
	 * @Column(type="boolean", name="news")
	 */
	private $news;

	/**
	 *
	 * @var bool
	 *
	 * @Column(type="boolean", name="unlocked")
	 */
	private $unlocked;

	/**
	 *
	 * @var Collection
	 *
	 * @ManyToMany(targetEntity="Model\Gallery\Gallery")
     * @JoinTable(name="article_article_galleries",
     *      joinColumns={@JoinColumn(name="article_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="gallery_id", referencedColumnName="id")})
	 */
	private $galleries;

	/**
	 *
	 * @var Collection
	 *
	 * @ManyToMany(targetEntity="Model\User\User")
     * @JoinTable(name="article_article_authors",
     *      joinColumns={@JoinColumn(name="article_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="user_id", referencedColumnName="id")})
	 */
	private $authors;

	/**
	 *
	 * @var Collection
	 *
	 * @OneToMany(targetEntity="Model\Article\Attachment", mappedBy="article")
	 */
	private $attachments;
}





[DDC-33] Remove allowPartialObjects option. Created: 07/Oct/09  Updated: 15/Oct/09  Resolved: 15/Oct/09

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA2
Fix Version/s: 2.0-ALPHA3
Security Level: All

Type: Task Priority: Critical
Reporter: Roman S. Borschel Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None


 Description   

I think this option will cause unnecessary confusion. The best solution is to always disallow partial objects, yet you can force partial objects on individual object queries to increase performance if necessary. This is much simpler for the user than to remember all the details of how the current option affects certain behavior. Also, with the current default behavior of partial objects everywhere, some standard operations can unexpectedly not work, like adding an object to a collection of a managed object (but the collection itself was not fetched yet). As a result the collection will not be wrapped by doctrine with a PersistentCollection and modifications are lost.
There are more of such examples.

I will do this myself and I think this can even be done with full backwards compatibility (though its not strictly necessary since we're still in alpha).

This should be done before entering beta.






[DDC-32] EntityManager#getReference broken Created: 07/Oct/09  Updated: 07/Oct/09  Resolved: 07/Oct/09

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA2
Fix Version/s: 2.0-ALPHA3
Security Level: All

Type: Bug Priority: Critical
Reporter: Roman S. Borschel Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None


 Description   

.






[DDC-26] Add support for subdirectories in classdir when using schema-tool --create Created: 01/Oct/09  Updated: 05/Oct/09  Resolved: 05/Oct/09

Status: Closed
Project: Doctrine 2 - ORM
Component/s: Tools
Affects Version/s: None
Fix Version/s: 2.0-ALPHA2
Security Level: All

Type: Improvement Priority: Critical
Reporter: Ismo Toijala Assignee: Jonathan H. Wage
Resolution: Fixed Votes: 0
Labels: None


 Description   

Currently when using schema-tool --create, all entity classes have to be in one directory. Subdirectories are not supported and result in errors. The iterator tries to require the subdirectories. This makes it impossible to use schema-tool --create to create the database for models that use namespaces and follow Doctrine rules for placing the files in subdirectories.

The schema-tool should iterate through all of the subdirectories of the classdir to find all of the entity classes. It should also not try to require() any directories.



 Comments   
Comment by Roman S. Borschel [ 01/Oct/09 ]

Jon, I remember you mentioning this issue already. Did you fix it already?

Comment by Jonathan H. Wage [ 01/Oct/09 ]

No but I will fix it. The problem exists in Doctrine\ORM\Tools\Export\ClassMetadataExporter as well.

Comment by Guilherme Blanco [ 03/Oct/09 ]

We should make is an option, not recursive all the time.... maybe include as an optional parameter --recursive

I'll check it out the issue and will come with a solution later today.





[DDC-21] Already fetched associations should not be overriden by subsequent queries. Created: 25/Sep/09  Updated: 09/Oct/09  Resolved: 09/Oct/09

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

Type: Improvement Priority: Critical
Reporter: Roman S. Borschel Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None

Issue Links:
Dependency
depends on DDC-22 EntityManager#refresh() should also r... Closed

 Description   

The discussion about this was brought up by DC-41. After checking the behavior of other ORMs (notably Hibernate), already fetched associations should not be overridden by subsequent queries, just like with other persistent state of already fetched entities. This saves performance and can assure a better integrity of the object model in-memory.

Entities and their associations that are already in-memory should only be refreshed if this is done explicitly either through EntityManager#refresh($entity) or through using the Query::HINT_REFRESH query hint on any query.



 Comments   
Comment by Roman S. Borschel [ 25/Sep/09 ]

This behavior is already correct for single-valued associations but not for collections. Needs to be fixed in ObjectHydrator.





[DDC-22] EntityManager#refresh() should also refresh associations. Created: 25/Sep/09  Updated: 28/Oct/09  Resolved: 28/Oct/09

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

Type: Improvement Priority: Critical
Reporter: Roman S. Borschel Assignee: Roman S. Borschel
Resolution: Fixed Votes: 0
Labels: None

Issue Links:
Dependency
is required for DDC-21 Already fetched associations should n... Closed

 Description   

Initially this issue was brought up by DC-41 which in turn led to DDC-21. The implementation of DDC-21 requires a working refresh() implementation that also refreshes associations.

1) For the state of the entity that is refreshed itself this is self-explanatory (simple select on the primary table, this is what already works).

2) For single-valued associations the proper query depends on whether the entity being refreshed represents the owning side or the inverse side of the association. If it is the inverse side, a simple query like this should do:

select addresses.id, ... from addresses where addresses.user_id=?

If it is the owning side, a join may be required:

select addresses.id, ... from addresses inner join users on addresses.id = users.address_id where users.id=?

3) For one-to-many collections, a simple select on the target entity table, similar to the following should do:

select .... from phonenumbers ... where phonenumbers.user_id=?

For many-to-many collections a similar select that joins over the join table is required.

An clever way for collections might be to not trigger this SQL immediately on refresh() but to simply mark the collection as uninitialized again so that the first access would trigger the reload, similar to a lazy-load.

Note that the collection itself is refreshed, not the state of the entities contained therein.
Also note that only associations need to be refreshed that were already initialized. If an associated collection is uninitialized, it does not need to be refreshed. If an associated single-valued proxy is uninitialized, it does not need to be refreshed.






[DDC-2] Proxies in UoW::_computeChangeSets Created: 09/Sep/09  Updated: 06/Oct/09  Resolved: 06/Oct/09

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

Type: Bug Priority: Critical
Reporter: Roman S. Borschel Assignee: Roman S. Borschel
Resolution: Fixed Votes: 1
Labels: None


 Description   

When having a proxy object, say "PhonenumberProxy? extends Phonenumber", and its not yet loaded from the database I think an error occures in the UnitOfWork::_computeChangeSets function since it goes and retrieves that lazy load object value using an instance of "ReflectionProperty?". However with it being lazily loaded the value must be null.






[DDC-3037] cslssl Created: 18/Mar/14  Updated: 18/Mar/14  Resolved: 18/Mar/14

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

Type: Bug Priority: Major
Reporter: Cslssl Assignee: Marco Pivetta
Resolution: Incomplete Votes: 0
Labels: None





[DDC-2972] [GH-948] Update UnitOfWork.php Created: 10/Feb/14  Updated: 10/Feb/14  Resolved: 10/Feb/14

Status: Closed
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: Invalid Votes: 0
Labels: None


 Description   

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

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

Message:

For datetime objects the comparison doesn't work ex:
array (size=2)
0 =>
object(DateTime)[990]
public 'date' => string '2007-10-25 00:00:00' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'Europe/Luxembourg' (length=17)
1 =>
object(DateTime)[1876]
public 'date' => string '2007-10-25 00:00:00' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'Europe/Luxembourg' (length=17)

it's the same date but the scrict comparison make the original value is different of the actual value.



 Comments   
Comment by Doctrine Bot [ 10/Feb/14 ]

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

Comment by Alexander [ 10/Feb/14 ]

http://docs.doctrine-project.org/en/latest/cookbook/working-with-datetime.html





[DDC-2857] [GH-877] [WIP] Add failing test for DDC-1787. Created: 14/Dec/13  Updated: 14/Dec/13  Resolved: 14/Dec/13

Status: Closed
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: Marco Pivetta
Resolution: Duplicate Votes: 0
Labels: None


 Description   

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

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

Message:

Using joined table inheritance, when persisting multiple new entities
that are subclasses of a baseclass that has the @Version attribute set,
only the last persisted entity will have it's version set.



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

Duplicate of DDC-1787

Comment by Doctrine Bot [ 14/Dec/13 ]

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





[DDC-2752] Item order lost using paginator Created: 20/Oct/13  Updated: 13/Dec/13  Resolved: 13/Dec/13

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

Type: Bug Priority: Major
Reporter: Kristof Mariën Assignee: Benjamin Eberlei
Resolution: Won't Fix Votes: 0
Labels: paginator


 Description   

We are using the doctrine pagination tool for faster queries in paginated results.

But doctrine is now creating the following query:

SELECT DISTINCT id0 FROM (
SELECT c0_.id AS id0, c0_.number AS number1
FROM cudi.stock_orders_items c0_
INNER JOIN cudi.stock_orders c1_ ON c0_.order_id = c1_.id
WHERE c1_.date_ordered IS NOT NULL AND c1_.date_ordered > $1 AND c1_.date_ordered < $2
ORDER BY c1_.date_ordered DESC
) dctrn_result LIMIT 25 OFFSET 50

But due to the distinct, the order is lost and the results are not sorted by date_ordered anymore. How can this be solved?

Thanks



 Comments   
Comment by Marco Pivetta [ 20/Oct/13 ]

Kristof Coomans is the order lost already in this result or in the `WHERE IN()` subsequent query?

Comment by Kristof Mariën [ 20/Oct/13 ]

I was digging in the paginator code and this is the query used to select the ids in \Doctrine\ORM\Tools\Pagination\Paginator (line 173)

The subquery from above, outputs the results in the right order. But after applying the distinct the order is messed up. I think this problem needs to be solved by the preserveSqlOrdering function in LimitSubqueryOutputWalker. But this function doesn't add a column to sort on...

Comment by Benjamin Eberlei [ 26/Oct/13 ]

Kristof Mariën Since you have the example already, so you mean the ORDER BY has to be part of the subquery and ALSO added to the outer query? That actually makes sense.

Comment by Kristof Mariën [ 28/Oct/13 ]

That would solve the problem for me.

Comment by Kristof Mariën [ 20/Nov/13 ]

Any progress on this issue?

Comment by Kristof Mariën [ 04/Dec/13 ]

I have found another query with the same problem. The common thing they have is that I want to order on a column of a joined entity.

Comment by Kristof Mariën [ 06/Dec/13 ]

After digging in the code I found that I just had to add the joined entity to my select statement. This issue can be closed





[DDC-2703] UnitOfWork should not compute the change set on updated but not-persisted entities. Created: 24/Sep/13  Updated: 24/Sep/13  Resolved: 24/Sep/13

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

Type: Bug Priority: Major
Reporter: Juti Noppornpitak Assignee: Guilherme Blanco
Resolution: Invalid Votes: 0
Labels: None
Environment:

PHP 5.3 with SQLite 3 and PHP 5.4 with MySQL 5.5



 Description   

Problem:
UnitOfWork computes the change set on updated but not-persisted entities.

How to reproduce:

1. Suppose I have 2 entities of class Node stored on the database of choices.
2. Load the entities via the respective repository (to ensure that the unit of work manages them).
3. Update something on both entities.
4. Only store one of them.

Expectation:

Any changes on the entity which is not persisted must not be stored in the database.

Actual Result:

The changes are saved.

Use the example:

1. Clone the demo app from git@github.com:shiroyuki/trphp13-demo.git.
2. Run the preparation commands to create the database (one DB called "trphp13"), schema (one table called "product") and load fixtures (3 entities).
3. Run app/console sandbox:case0 to recreate the bug.

Note:

I traced the bug down to computeChangeSet and it seems that even though the entity is not scheduled for dirty checks, the unit of work still computes the change set of the problematic entity. From the provided example, the node named "Node 2" should not be updated to "B" when the CaseZero command is executed.



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

Juti Noppornpitak we are not going to checkout your project for this. Please make a small example that uses ONLY the ORM, with no other involved frameworks.

You should be able to do that in a single php script that includes:

1) the involved entities
2) an initialization of the ORM
3) the functional example

we can then convert that into a unit test once it has been verified.

Comment by Guilherme Blanco [ 24/Sep/13 ]

This should be related to change tracking policy.
Doctrine uses IMPLICIT change tracking policy by default, applying an algorithm called persist-by-reachability.
To fix your issue, you need to modify your change tracking to DEFERRED_EXPLICIT or NOTIFY.

Here is a more detailed explanation:

So the change you need to do is: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/change-tracking-policies.html

/**
 * @ORM\Entity
 * @ORM\ChangeTrackingPolicy("DEFERRED_EXPLICIT")
 */
class Node
{
    // ...
}
Comment by Guilherme Blanco [ 24/Sep/13 ]

It's an issue of misunderstanding change tracking policies.

Comment by Juti Noppornpitak [ 24/Sep/13 ]

Thank you.





[DDC-2602] Unable to query for entities on postLoad event Created: 07/Aug/13  Updated: 19/Aug/13  Resolved: 19/Aug/13

Status: Closed
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: Git Master
Fix Version/s: 2.x, Git Master
Security Level: All

Type: Bug Priority: Major
Reporter: Guilherme Blanco Assignee: Guilherme Blanco
Resolution: Fixed Votes: 0
Labels: None


 Comments   
Comment by Guilherme Blanco [ 19/Aug/13 ]

implemented fix





[DDC-2463] [GH-675] Implementation for 'IsNot'-Comparison Created: 20/May/13  Updated: 30/Jun/13  Resolved: 26/May/13

Status: Closed
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: Won't Fix Votes: 0
Labels: None


 Description   

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

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

Message:

See PR (https://github.com/doctrine/collections/pull/11)

This is the required implementation for 'IsNotNull'-Filters in Collection-Filtering.



 Comments   
Comment by Alexander [ 26/May/13 ]

Already fixed with:
http://www.doctrine-project.org/jira/browse/DDC-2471

Comment by Doctrine Bot [ 30/Jun/13 ]

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





[DDC-2453] [GH-668] [WIP] Adding failing test for DDC-2452 Created: 16/May/13  Updated: 24/Jun/13  Resolved: 16/May/13

Status: Closed
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: Marco Pivetta
Resolution: Duplicate 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/668

Message:

DQL joins between JTI entities produce invalid SQL when additional conditions are inserted via WITH clause

Still working on a fix



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

Duplicate of DDC-2452

Comment by Doctrine Bot [ 24/Jun/13 ]

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





[DDC-2444] NULL IN CASE WHEN Created: 12/May/13  Updated: 22/May/13  Resolved: 22/May/13

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

Type: Bug Priority: Major
Reporter: vahid sohrabloo Assignee: Guilherme Blanco
Resolution: Won't Fix Votes: 0
Labels: None


 Description   

Hi
In DQL when i use NULL IN "CASE WHEN" like this
"AVG(CASE WHEN g.speed > 0 THEN g.speed ELSE NULL END)"
Throw this expestion
Unexpected 'NULL'



 Comments   
Comment by Miha Vrhovnik [ 14/May/13 ]

We could say a duplicate of: DDC-2208

Comment by Guilherme Blanco [ 22/May/13 ]

After further investigation, JPA 2.0 and 2.1 do not support NULL as part of ScalarExpression.
There are many underlying problems by adding this straight to ScalarExpression, such as the example I showed.
I don't think supporting this will bring benefits, but too many headaches.
As a workaround, create your own function that generates "NULL" as SQL. It would work perfectly here.
Closing the PR as we will not support it.





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

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

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


 Description   

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

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

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

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

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



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

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

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

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

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

Because the DDC-2220 is closed.

Comment by Benjamin Eberlei [ 11/Sep/13 ]

We won't add this feature.

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

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

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

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

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

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

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

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

Comment by Benjamin Eberlei [ 12/Sep/13 ]

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

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





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

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

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

OSX, PHP 5.4.9



 Description   

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

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

When I unserialize said entity with this code:

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

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

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



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

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

Comment by Quintenvk [ 12/Apr/13 ]

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





[DDC-2397] [GH-647] Bugfix/ddc 1048 cordoval Created: 10/Apr/13  Updated: 12/Apr/13  Resolved: 12/Apr/13

Status: Closed
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: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: None


 Description   

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

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

Message:



 Comments   
Comment by Luis Cordova [ 10/Apr/13 ]

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

please check ^^

Comment by Doctrine Bot [ 12/Apr/13 ]

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





[DDC-2393] Doctrine ORM put null to relation field when write persisting Created: 07/Apr/13  Updated: 07/Apr/13  Resolved: 07/Apr/13

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

Type: Bug Priority: Major
Reporter: Nikita Assignee: Marco Pivetta
Resolution: Incomplete Votes: 0
Labels: None
Environment:

symfony2.2



 Description   

There is my bundle, for more details:
https://github.com/hell0w0rd/bad-doctrine-entities



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

Can you please make an example of what the failure you're experiencing looks like? What is being done? What is the expected result? What is the experienced behaviour?

Comment by Nikita [ 07/Apr/13 ]

When controller persist object, I'm expecting orm put not null into relation field in fact it is not so.

Comment by Marco Pivetta [ 07/Apr/13 ]

Nikita the example at https://github.com/hell0w0rd/bad-doctrine-entities/blob/master/DeskBundle/Controller/PostController.php#L15-L21 is not enough to open an issue. Can you please build a simple script that does not involve third party components and that reproduces your problem? It should work only with the ORM.

Comment by Nikita [ 07/Apr/13 ]

My issue is closely connected with third party components, because they decouple from each other - is not to decide

Comment by Marco Pivetta [ 07/Apr/13 ]

Then it's impossible for us to decide what the cause is. I'm closing this one - consider reproducing the problem locally and then deciding whether this is an ORM or a symfony form problem.





[DDC-2389] [GH-642] replaced direct class in instance creation Created: 04/Apr/13  Updated: 04/Apr/13  Resolved: 04/Apr/13

Status: Closed
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: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: None


 Description   

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

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

Message:

return new EntityManager() -> return new static() on line 945
made code more reusable



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

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

Comment by Marco Pivetta [ 04/Apr/13 ]

EntityManager should not be extended





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

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

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


 Description   

Hi,

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

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

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

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

Thanks



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

duplicate of DDC-2217





[DDC-2375] Join with multiples tables Created: 27/Mar/13  Updated: 27/Mar/13  Resolved: 27/Mar/13

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

Type: New Feature Priority: Major
Reporter: Adriano Crivelari Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: None


 Description   

Dear Friends, I've a question about Join with multiple tables.
I've 3 tables: Country, State, City, and I need get country_name from City Entity.
Any suggestion?

Table City:
city_id
state_id
city_name

Table State
state_id
country_id
state_name

Table Country
country_id
country_name

This is my Entity City:

<?php

namespace System\Entity;

use Doctrine\ORM\Mapping as ORM,
Doctrine\Common\Collections\ArrayCollection;

/**

    SysCity
    *
    @ORM\Table(name="sys_city")
    @ORM\Entity(repositoryClass="System\Entity\SysCityRepository")
    */
    class SysCity
    {
    /*
    Instantiate all methods gets and sets
    */

public function __construct($options = null)
{ Configurator::configure($this, $options); }

/**

    @var integer
    *
    @ORM\Column(name="id_city", type="integer", nullable=false)
    @ORM\Id
    @ORM\GeneratedValue(strategy="IDENTITY")
    */
    private $idCity;

/**

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

/**

    @var \SysState
    *
    @ORM\ManyToOne(targetEntity="System\Entity\SysState", inversedBy="state")
    @ORM\JoinColumns( { * @ORM\JoinColumn(name="id_state", referencedColumnName="id_state") * }

    )
    */
    private $idState;

/**

    @var \SysCountry
    *
    @ORM\ManyToMany(targetEntity="System\Entity\SysCountry", inversedBy="country")
    @ORM\JoinTable(name="sys_state",
    joinColumns= {@ORM\JoinColumn(name="id_state", referencedColumnName="id_state")}

    ,
    inverseJoinColumns= {@ORM\JoinColumn(name="id_country", referencedColumnName="id_country")}
    )
    */
    private $idCountry;

public function getIdCity()
{ return $this->idCity; }

public function setIdCity($idCity)
{ $this->idCity = $idCity; return $this; }

public function getCity()
{ return $this->city; }

public function setCity($city)
{ $this->city = $city; return $this; }

public function getIdState()
{ return $this->idState; }

public function setIdState($idState)
{ $this->idState = $idState; return $this; }

public function getIdCountry()
{ return $this->idCountry; }

public function setIdCountry($idCountry)
{ $this->idCountry = $idCountry; return $this; }

Thanks a lot!



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

This is an issue tracker, not a support forum. Please ask your questions on the http://groups.google.com/group/doctrine-user mailing list or on http://stackoverflow.com/ or on IRC on irc://irc.freenode.net#doctrine





[DDC-2357] [GH-620] Chaining for EM Created: 18/Mar/13  Updated: 18/Mar/13  Resolved: 18/Mar/13

Status: Closed
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: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: None


 Description   

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

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

Message:

Chaining for EM methods persist()/flush(), to write more elegant code $em->persist($account)->flush();



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

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

Comment by Marco Pivetta [ 18/Mar/13 ]

Fluid interfaces on the persistence API are discouraged





[DDC-2348] [GH-612] Fixed failing tests Created: 13/Mar/13  Updated: 14/Mar/13  Resolved: 14/Mar/13

Status: Closed
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: Invalid Votes: 0
Labels: None


 Description   

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

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

Message:



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

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





[DDC-2331] [GH-600] [PreUpdateEventArgs] Allows to add a new value on the entity changeset Created: 05/Mar/13  Updated: 05/Mar/13  Resolved: 05/Mar/13

Status: Closed
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: Invalid Votes: 0
Labels: None


 Description   

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

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

Message:

Hey!

I propose to add a `addNewValue` method on the `PreUpdateEventArgs`. This method allows to add a new value on the entity changeset when the entity changeset does not wrap the field.

In one of my app, I need to update a field if an entity is updated but the field is not updated at the beginning.



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

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





[DDC-2329] [GH-598] adds a new output format Created: 03/Mar/13  Updated: 05/Mar/13  Resolved: 05/Mar/13

Status: Closed
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: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: None


 Description   

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

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

Message:

same as doctrine/dbal#279



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

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





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

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

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

php 5.4.11, MySQL 5.5, ubuntu 12.10


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

 Description   

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

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

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

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

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

Finally, i tried to comment the test

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

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



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

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

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

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

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

but if i add this after:

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

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

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

Comment by Marco Pivetta [ 24/Feb/13 ]

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

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

Bug found!

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

array('by_reference"=>false)

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

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

Comment by Marco Pivetta [ 26/Feb/13 ]

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





[DDC-2299] [GH-582] Test for DDC-2106 Created: 16/Feb/13  Updated: 31/Jul/13  Resolved: 26/Feb/13

Status: Closed
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: Marco Pivetta
Resolution: Duplicate Votes: 0
Labels: None


 Description   

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

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

Message:



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

Duplicate of DDC-2106

Comment by Doctrine Bot [ 31/Jul/13 ]

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





[DDC-2303] @param wrong in Doctrine\ORM\PersistentCollection::__constructor Edit Created: 18/Feb/13  Updated: 26/Feb/13  Resolved: 26/Feb/13

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

Type: Bug Priority: Major
Reporter: Torsten Granek Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: collection

Attachments: JPEG File screenshot-1.jpg    

 Description   

When i try to generate a new PersistentCollection like this:
###############################################
$collection = new ArrayCollection();
new \Doctrine\ORM\PersistentCollection(
$this->getEntityManager(),
new ClassMetadata(''),
$collection
);
###############################################
i get an typ hinting error like
"Expected array, got "Doctrine\Common\Collections\ArrayCollection"

This could be fixed by changing the type hinting for the Doctrine\ORM\PersistentCollection::__constructor
_From:_
###############################################
/**

  • Creates a new persistent collection.
    *
  • @param EntityManager $em The EntityManager the collection will be associated with.
  • @param ClassMetadata $class The class descriptor of the entity type of this collection.
  • @param array $coll The collection elements.
    */
    public function __construct(EntityManager $em, $class, $coll)
    {
                                                                                              1. _To:_
                                                                                                ###############################################
                                                                                                /**

  • Creates a new persistent collection.
    *
  • @param EntityManager $em The EntityManager the collection will be associated with.
  • @param ClassMetadata $class The class descriptor of the entity type of this collection.
  • @param \ArrayAccess $coll The collection elements.
    */
    public function __construct(EntityManager $em, $class, $coll)
    {
    ###############################################


 Comments   
Comment by Torsten Granek [ 18/Feb/13 ]

When i try to generate a new PersistentCollection like this:


     $collection = new ArrayCollection();
     new \Doctrine\ORM\PersistentCollection(
				$this->getEntityManager(),
				new ClassMetadata(''),
				 $collection
			);

I get an typ hinting error like
"Expected array, got "Doctrine\Common\Collections\ArrayCollection"

This could be fixed by changing the type hinting for the Doctrine\ORM\PersistentCollection::__constructor
_From:_

     /**
     * Creates a new persistent collection.
     *
     * @param EntityManager $em    The EntityManager the collection will be associated with.
     * @param ClassMetadata $class The class descriptor of the entity type of this collection.
     * @param array       $coll  The collection elements.
     */
    public function __construct(EntityManager $em, $class, $coll)
    {

_To:_

     /**
     * Creates a new persistent collection.
     *
     * @param EntityManager $em    The EntityManager the collection will be associated with.
     * @param ClassMetadata $class The class descriptor of the entity type of this collection.
     * @param \ArrayAccess $coll  The collection elements.
     */
    public function __construct(EntityManager $em, $class, $coll)
    {

Comment by Christophe Coevoet [ 18/Feb/13 ]

There is no typehint in the PersistentCollection constructor. So the issue cannot come from this place (the phpdoc is wrong btw, it expects a Collection, not an array)

Please give the full error, i.e. the message and the location so that we can know where it happens.

Comment by Torsten Granek [ 20/Feb/13 ]

There error is not in the function declaration, it is in the @param in the doc block of the constructor.

Using PHPStorm as IDE i got this error thrown by the IDE it self, not php. (Screenshot will be attached)

Using ZF2 the error is on line 121 at:
vendor/doctrine/orm/lib/Doctrine/ORM/PersistentCollection.php

Comment by Torsten Granek [ 20/Feb/13 ]

Using PHPStorm as IDE i got "Expected array, got "Doctrine\Common\Collections\ArrayCollection" thrown by the IDE it self, not php.

Comment by Torsten Granek [ 20/Feb/13 ]

Using PHPStorm as IDE i got "Expected array, got "Doctrine\Common\Collections\ArrayCollection" thrown by the IDE it self, not php.

Comment by Marco Pivetta [ 26/Feb/13 ]

The correct type hint here is `Doctrine\Common\Collections\Collection`.

I'm closing this as invalid, since you shouldn't instantiate a persistent collection on your own. Consider opening a pull request at https://github.com/doctrine/doctrine2 instead if you want to fix the typehint.





[DDC-2278] Invalid arguments to PreFlushEventArgs class Created: 05/Feb/13  Updated: 05/Feb/13  Resolved: 05/Feb/13

Status: Closed
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: Stanislav Anisimov Assignee: Marco Pivetta
Resolution: Duplicate Votes: 0
Labels: None


 Description   

Here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/UnitOfWork.php#L527 PreFlushEventArgs expects number of arguments to be 2 and the first argument have to be instance of entity manager. But two arguments are passed and the first one is not instanceof em.



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

Being handled in DDC-2276





[DDC-2259] [GH-557] [DDC 2004] addFilter class name or instance Created: 26/Jan/13  Updated: 28/Mar/14  Resolved: 26/Jan/13

Status: Closed
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: Invalid Votes: 0
Labels: None


 Description   

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

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

Message:

Make it possible to add filter class name or instance to addFilter. This is useful to use services to inject other dependencies.



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

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

Comment by Doctrine Bot [ 28/Mar/14 ]

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





[DDC-2255] [Doctrine-Bridge][Console] Entity, Getters and Setters Generating Bug detected in Symfony 2 Framework Created: 24/Jan/13  Updated: 24/Jan/13  Resolved: 24/Jan/13

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

Type: Bug Priority: Major
Reporter: Ala Eddine Khefifi Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: collection


 Description   

Bug found when generation the Entity, Getters and Setters by using the Command:

> php app/console doctrine:generate:entities YourBundleBundle:YourEntity 

In the situation you have a OneToMany relation in the Entity and you did implement the __construct(), then the Console Wont generate the ArrayCollection() !
In the case you did not implement the __construct(), then everything will goes fine when generating them,
Example:

/**
 * @ORM\OneToMany(targetEntity=" YourBundleBundle \Entity\ YourEntity ", mappedBy=" YourEntity ")
 */
private $YourAttribut;

public function __construct()
{
  $this-> YourAttribut = new \Doctrine\Common\Collections\ArrayCollection();
} 
// But in the case you did implement the __construct() before using the Command, let say like this:

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

In this case, when using the Command to generate Entity, Getters and Setters, the Console Wont generate the ArrayCollection() of the OneToMany relations in the __construct() !



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

Ala Eddine Khefifi This is expected behavior, since the generator should not change already existing methods

Comment by Ala Eddine Khefifi [ 24/Jan/13 ]

but it could override them and add missing instruction that should be added within the code, otherwise it leads to a dis-function and non stable relations !!

Comment by Marco Pivetta [ 24/Jan/13 ]

No, that is not up to the generator. Entity generation and fixing your broken existing code are different things. You should not rely on the generator to handle this kind of problems, the generator just gives you a kick-start, but after that, you are on your own.





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

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

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


 Description   

I have the following code:

$new = new InterviewReview();

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

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

When i execute this code i have the following error:

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

Column 'interview_review_id' cannot be null

Here are my entities:

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

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

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

        return $this;
    }

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

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


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

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

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

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

        return $this;
    }

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

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

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



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

Fixing code highlighting

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

Fixed

Comment by Marco Pivetta [ 15/Jan/13 ]

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

Comment by Marco Pivetta [ 15/Jan/13 ]

Calling

$question->setInterviewReview($this);

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

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

In composer (using symofny) i have:

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

and got the latest version.

Lanuched composer update 2 hours ago

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

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

{"persist"}

will do this magic

Comment by Marco Pivetta [ 15/Jan/13 ]

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

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

In the documentation there is some info about this:

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

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

Comment by Marco Pivetta [ 15/Jan/13 ]

Paweł Łaskarzewski see DDC-2227

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

Ok thanks for your help





[DDC-2242] [GH-550] Update lib/Doctrine/ORM/UnitOfWork.php Created: 15/Jan/13  Updated: 22/Mar/14  Resolved: 15/Jan/13

Status: Closed
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: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: None


 Description   

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

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

Message:

When the pk contains a DateTime object doctrine fail to create the index, because implode call __toString wich doesn't exists in \DateTime object



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

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

Comment by Doctrine Bot [ 22/Mar/14 ]

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





[DDC-2208] CASE WHEN ... WHEN doesn't work Created: 19/Dec/12  Updated: 22/May/13  Resolved: 22/May/13

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

Type: Bug Priority: Major
Reporter: Miha Vrhovnik Assignee: Guilherme Blanco
Resolution: Won't Fix Votes: 0
Labels: None


 Description   

Having the following part in select DQL throws an exception.

SUM(CASE
            WHEN c.startDate <= :start THEN c.endDate - :start
            WHEN c.endDate >= :end THEN :end - c.startDate
            ELSE 0
            END) 

exception:

[Syntax Error] line 0, col 124: Error: Expected Doctrine\ORM\Query\Lexer::T_ELSE, got '-' 

It seems that it's failing inside the second THEN

This one also seems to fail:

SUM(CASE
            WHEN c.startDate <= :start THEN (c.endDate - :start)
            WHEN c.endDate >= :end THEN (:end - c.startDate)
            ELSE 0
            END) 

exception:

[Syntax Error] line 0, col 60: Error: Unexpected '(' 

Another one:

SUM(CASE
                WHEN c.startDate <= :start THEN c.endDate - :start
                WHEN c.endDate >= :end THEN :end - c.startDate
                ELSE 0
                END) = :result FROM ...

exception:

[Syntax Error] line 0, col 60: Error: Expected Doctrine\ORM\Query\Lexer::T_FROM, got '=' 


 Comments   
Comment by Miha Vrhovnik [ 20/Dec/12 ]

I've added two more cases where the parsing fails. Do you want a separate tickets for that?

Comment by Fabio B. Silva [ 20/Dec/12 ]

Don't worry, I'll spend some time over this...
But I'm not sure about the last one.

Comment by Miha Vrhovnik [ 20/Dec/12 ]

The 3rd case seems work just fine as a part of a HAVING clause.
I haven't tried it but It might be that it fails with something simpler like SELECT COUNT( * ) = :foo FROM ... or SELECT COUNT( * ) = 2 FROM ...

Comment by Miha Vrhovnik [ 08/Jan/13 ]

Fabio I have two more...
It doesn't like NULL and subselect after then part

 
->addSelect('CASE
    WHEN po.quantity IS NULL THEN NULL
    ELSE po.quantity -
            COALESCE(0, (
                SELECT COUNT(rd.product) FROM xxxx rd
                    WHERE (rd.startDate <= :end) AND (rd.endDate >= :start) AND
                        rd.product = c.product)))
    END
    AS po.quantity
')

:edit replaced with real query

Comment by Miha Vrhovnik [ 08/Jan/13 ]

addon: well the subquery part can be full query with joins ....

Comment by Guilherme Blanco [ 22/May/13 ]

After further investigation, JPA 2.0 and 2.1 do not support NULL as part of ScalarExpression.
There are many underlying problems by adding this straight to ScalarExpression, such as the example I showed.
I don't think supporting this will bring benefits, but too many headaches.
As a workaround, create your own function that generates "NULL" as SQL. It would work perfectly here.
Closing the PR as we will not support it.

Comment by Miha Vrhovnik [ 22/May/13 ]

Not to sound rude but, the answer is far fetched. So what if JPA is not supporting it. Yes I understand that the Doctrine is modeled after JPA but this shouldn't mean that it's not better in some regards.

This is really a low blow especially if there is a need to use a query builder to build the queries. And as I said it's not only the IS NULL but the CASE statement can contain a whole subquery with it's own CASE statements etc...





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

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

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

Linux, Symfony 2, PHP 5.3.10



 Description   

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

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

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

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

  • using the Expr class:

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

  • alternatively:

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

  • even direct DQL:

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

The generated DQL looks fine:

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

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

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



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

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

Comment by Marco Pivetta [ 28/Nov/12 ]

Moritz Kraft what was it exactly?

Comment by Moritz Kraft [ 29/Nov/12 ]

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





[DDC-2163] Export entity data to array and create new entity by this array Created: 23/Nov/12  Updated: 27/Nov/12  Resolved: 23/Nov/12

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

Type: Improvement Priority: Major
Reporter: Anton Assignee: Benjamin Eberlei
Resolution: Won't Fix Votes: 0
Labels: serialize


 Description   

Entity serialization is really pain operation for doctrine2 entities, but why we need serialization? If we may just get array of table's row for entity and store this array anywhere!

For example, we have Entity:

id, category_id, title

(where category_id is many to one to Category entity)

If we will able to get just array from entity like
array(
'id' => 1,
'category_id' => 2,
'title' => 'Some title'
)
That's all!

I look at code and find a place where table row converted to object: https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php#L341

This method is protected, so we can't call it directly. Can we change it to public?

Another question how we can get this raw values array from entity. I found method https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/UnitOfWork.php#L2692 but it return data with related entities.



 Comments   
Comment by Anton [ 23/Nov/12 ]

i write some weird code: http://stackoverflow.com/questions/13507300/doctrine2-export-entity-to-array/13522452#13522452
please, take a look.

Comment by Marco Pivetta [ 23/Nov/12 ]

Anton the namespace `Internal` is there for a reason. If you want to convert entities to array or the opposite, please use either JMS Serializer, Symfony Serializer or Zend\StdLib\Hydrator with DoctrineModule\StdLib\Hydrator.

Currently, we don't support serialization

Comment by Marco Pivetta [ 23/Nov/12 ]

Anton this is not the correct approach to the problem. Serialization/unserialization is a problem related to (probably) Doctrine\Common.

Comment by Anton [ 27/Nov/12 ]

Marco Pivetta, thanks for reply. With JMSSerializer or Symfony serializer can i later insert\update object in db? I see in sources, that UnitOfWork get changeset for each entity. How doctrine2 knows which properties of serialized\deserialized entitiy was changed?





[DDC-2074] ManyToManyPersister not found in the chain configured namespaces Created: 12/Oct/12  Updated: 25/Nov/12  Resolved: 25/Nov/12

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.2.3
Fix Version/s: 2.3.1
Security Level: All

Type: Bug Priority: Major
Reporter: Steffan Harries Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: None
Environment:

Symfony 2.1



 Description   

The error is: "The class 'Doctrine\ORM\Persisters\ManyToManyPersister' was not found in the chain configured namespaces"

Replicate by making an entity which has a property which is self referencing; e.g. http://docs.doctrine-project.org/en/latest/reference/association-mapping.html#many-to-many-self-referencing .

For example an Album could be related to any other similar albums. An album entity would have a property 'relatedAlbums' which is an ArrayCollection. Similarly, I could be working on a CMS where any piece of content could be related to any other in order to show a "related content" or "related posts" style list on a web page.

Using Symfony 2.1 and a Symfony Form with FormBuilder make sure to use the 'by_reference' => false to call the setter for the property. In the setter for the property: https://gist.github.com/3879169

A similar question has been asked on StackOverflow: http://stackoverflow.com/questions/12077084/doctrine2-manytomany-self-referencing



 Comments   
Comment by Benjamin Eberlei [ 12/Oct/12 ]

I need a stacktrace for this error, i have no clue why this happens and where.

Comment by Steffan Harries [ 15/Oct/12 ]

Stack Trace:

The class 'Doctrine\ORM\Persisters\ManyToManyPersister' was not found in the chain configured namespaces Gedmo\Tree\Entity, Gedmo\Translatable\Entity, MyProject\Bundle\AdminBundle\Entity, MyProject\Bundle\Common\SiteBundle\Entity, MyProject\Bundle\Common\ContentBundle\Entity, FOS\UserBundle\Entity

500 Internal Server Error - MappingException

Stack Trace

in /opt/local/apache2/htdocs/projects/my-project/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/MappingException.php at line 38
*/
public static function classNotFoundInNamespaces($className, $namespaces)

{ return new self("The class '" . $className . "' was not found in the ". "chain configured namespaces " . implode(", ", $namespaces)); }

at MappingException ::classNotFoundInNamespaces ('Doctrine\ORM\Persisters\ManyToManyPersister', array('Gedmo\Tree\Entity', 'Gedmo\Translatable\Entity', 'MyProject\Bundle\AdminBundle\Entity', 'MyProject\Bundle\Common\SiteBundle\Entity', 'MyProject\Bundle\Common\ContentBundle\Entity', 'FOS\UserBundle\Entity'))
in /opt/local/apache2/htdocs/projects/my-project/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/Driver/MappingDriverChain.php at line 114
at MappingDriverChain ->loadMetadataForClass ('Doctrine\ORM\Persisters\ManyToManyPersister', object(ClassMetadata))
in /opt/local/apache2/htdocs/projects/my-project/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php at line 112
at ClassMetadataFactory ->doLoadMetadata (object(ClassMetadata), null, false, array())
in /opt/local/apache2/htdocs/projects/my-project/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php at line 302
at AbstractClassMetadataFactory ->loadMetadata ('Doctrine\ORM\Persisters\ManyToManyPersister')
in /opt/local/apache2/htdocs/projects/my-project/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php at line 205
at AbstractClassMetadataFactory ->getMetadataFor ('Doctrine\ORM\Persisters\ManyToManyPersister')
in /opt/local/apache2/htdocs/projects/my-project/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php at line 268
at EntityManager ->getClassMetadata ('Doctrine\ORM\Persisters\ManyToManyPersister')
in /opt/local/apache2/htdocs/projects/my-project/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/ManyToManyPersister.php at line 169
at ManyToManyPersister ->_getDeleteSQL (object(PersistentCollection))
in /opt/local/apache2/htdocs/projects/my-project/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/AbstractCollectionPersister.php at line 89
at AbstractCollectionPersister ->delete (object(PersistentCollection))
in /opt/local/apache2/htdocs/projects/my-project/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php at line 328
at UnitOfWork ->commit (null)
in /opt/local/apache2/htdocs/projects/my-project/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php at line 355
at EntityManager ->flush (null)
in kernel.root_dir/cache/dev/jms_diextra/doctrine/EntityManager_5075974d574d6.php at line 362
at EntityManager ->flush ()
in /opt/local/apache2/htdocs/projects/my-project/src/MyProjectBundle/Common/ContentBundle/Controller/ContentController.php at line 170
at ContentController ->updateAction (object(Request), '3')
at call_user_func_array (array(object(ContentController), 'updateAction'), array(object(Request), '3'))
in kernel.root_dir/bootstrap.php.cache at line 1421
at HttpKernel ->handleRaw (object(Request), '1')
in kernel.root_dir/bootstrap.php.cache at line 1385
at HttpKernel ->handle (object(Request), '1', true)
in kernel.root_dir/bootstrap.php.cache at line 1561
at HttpKernel ->handle (object(Request), '1', true)
in kernel.root_dir/bootstrap.php.cache at line 612
at Kernel ->handle (object(Request))
in /opt/local/apache2/htdocs/projects/my-project/web/app_dev.php at line 28

Comment by Benjamin Eberlei [ 25/Nov/12 ]

Ok apparently this is fixed





[DDC-2045] Unit of work use all columns for insert Created: 27/Sep/12  Updated: 13/May/13  Resolved: 23/Jan/13

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

Type: Bug Priority: Major
Reporter: Covie X Assignee: Marco Pivetta
Resolution: Won't Fix Votes: 0
Labels: None
Environment:

PHP 5.4.7--pl0-gentoo mysql Ver 14.14 Distrib 5.5.22, for Linux (x86_64)



 Description   

I use MySQL. And I'm OK with default values that will be assigned by DB for columns which values I don't set explicitly. But Doctrine seems to unable to skip some columns when building insert SQL query.

People suggest to use nullable flag to enable desired behaviour. And I don't see how it could help. I checked UnitOfWork.php and BasicEntityPersister.php. There is nothing about nullable.
And doc http://docs.doctrine-project.org/en/latest/reference/limitations-and-known-issues.html says that you cannot use custom persisters so far.

So why not track changes for unsaved entities as well, and don't force applications to generate more traffic with more SQL text and developers to set default values in entity constructors?

I would be glad if I'm mistaken and this feature is already implemented and you describe how to resolve the issue. Thanks



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

Covie X the `nullable` flag is a mapping used in columns. See http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html#annref-column

Also, Doctrine does not skip columns since default DB-side values are not supported by the ORM. To have default values, you usually set them in the entity's constructor.

Comment by Covie X [ 13/May/13 ]

Marco, you should be ashamed of the way you treat issues.
RTFM answer when there is real and huge problem, seriously?!





[DDC-2033] Merge with multiple Associations to the same Entity Created: 17/Sep/12  Updated: 23/Jan/13  Resolved: 23/Jan/13

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

Type: Bug Priority: Major
Reporter: sören jahns Assignee: Marco Pivetta
Resolution: Duplicate Votes: 1
Labels: merge
Environment:

Symfony 2.1.1, Ubuntu, PHP 5.3.5


Attachments: File Group.php     File User.php    

 Description   

Let's say we have 2 Entities. User and Group and there's a ManyToMany Assocication and an additional ManyToOne (User as owning side and no inverse).

So a User can have as many Groups as he likes and one another with the ManyToOne Association which can be also in the ManyToMany Collection. (Could be the MainGroup or something)

I create a User and add a Group(already in DB) and set the same as the ManyToOne and Merge it. Everything works fine as long as the Group in ManyToOne Association is not in the ManyToMany.

If I var_dump the merged entity i can already see that one association is empty.

It looks like doctrine is writing just one association of that Group preferring which one comes first. So if i change the position of the properties in the class the written association changes, but doctrine never writes both.

The reason why I use merge is that I normally store the entity in the session and merge and flush it in another request. But this also happens in the same Request.

In the UnitofWork at Line 2050 and 2053 are the responsible doMerge Calls for as CascadeMerge Tagged Associations. If Doctrine gets there in the first place the doMerge for the Group is running through. In the Second call when the Group is again associated with the user the doMerge already exits at line 1658. That's ok but I think there's something missing so doctrine isn't creating the association.

The Mentioned Entites are attached



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

Duplicate of DDC-1942





[DDC-1985] Call to undefined method ProxyException::proxyDirectoryNotWritable Created: 16/Aug/12  Updated: 17/Aug/12  Resolved: 17/Aug/12

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.2.3
Fix Version/s: 2.3
Security Level: All

Type: Bug Priority: Major
Reporter: Mark van der Velden Assignee: Guilherme Blanco
Resolution: Fixed Votes: 0
Labels: None


 Description   

I think it's fairly self explanatory, didn't supply a patch since I had no idea what text you wanted there

PHP Fatal error:  Call to undefined method Doctrine\ORM\Proxy\ProxyException::proxyDirectoryNotWritable() in .../orm/lib/Doctrine/ORM/Proxy/ProxyFactory.php on line 193


 Comments   
Comment by Guilherme Blanco [ 17/Aug/12 ]

This issue is already fixed in master





[DDC-1948] Lazy Loading on Many To One association does not work Created: 26/Jul/12  Updated: 21/Feb/13  Resolved: 21/Feb/13

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

Type: Bug Priority: Major
Reporter: Julien AUBIN Assignee: Marco Pivetta
Resolution: Incomplete Votes: 0
Labels: None


 Description   

Create a many to one relationship with lazy loading as exposed there :
http://stackoverflow.com/questions/7599007/lazy-loading-properties-not-loading-in-doctrine-2-0

Notice that the relationship does not load while it should.

The problem is always reproducible.



 Comments   
Comment by Benjamin Eberlei [ 29/Jul/12 ]

I need more information. The mapping of both entities, and a \Doctrine\Common\Utils\Debug::dump() of the $source entity when its a proxy. Also it would be helpful to have an SQL log which shows the queries executed by your example. Do you use any listeners?

Comment by Marco Pivetta [ 21/Feb/13 ]

Closing as incomplete.

Please test this with latest master before eventually re-opening





[DDC-1936] [GH-404] DDC-1933 - Fixing cloning of QueryBuilder and adding related tests Created: 19/Jul/12  Updated: 10/Nov/13  Resolved: 23/Jul/12

Status: Closed
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: Marco Pivetta
Resolution: Fixed 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/404

Message:

This PR fixes DDC-1933 and mimics the behaviour of `Doctrine\ORM\AbstractQuery` in `Doctrine\ORM\QueryBuilder` when dealing with assigned parameters and `__clone`.



 Comments   
Comment by Benjamin Eberlei [ 23/Jul/12 ]

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

Comment by Doctrine Bot [ 10/Nov/13 ]

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





[DDC-1933] Problem with parameters when clone Doctrine\ORM\QueryBuilder Created: 18/Jul/12  Updated: 23/Jul/12  Resolved: 23/Jul/12

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.3, Git Master
Fix Version/s: Git Master
Security Level: All

Type: Bug Priority: Major
Reporter: Gandzy Ghennady Assignee: Marco Pivetta
Resolution: Fixed Votes: 1
Labels: None


 Description   

Hi, here problem with cloning \Doctrine\ORM\QueryBuilder

Example
$queryBuilder = new QueryBuilder($em);

$queryBuilder->setParameter('parameter1', 'value1');

$copy = clone $queryBuilder;
$copy->setParameter('parameter2', 'value2');


count($queryBuilder->getParameters()) // equals 2
//expects 1


Solution:

QueryBuilder
public function __clone
{
   ......

   $this->parameters = clone $this->parameters;
}


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

Is `$copy = clone $queryBuilder();` a typo?

Comment by Gandzy Ghennady [ 18/Jul/12 ]

Sorry, this is a typo, was meant: $copy = clone $queryBuilder;

Comment by Marco Pivetta [ 20/Jul/12 ]

This is being handled at DDC-1936 (https://github.com/doctrine/doctrine2/pull/404)

Comment by Gandzy Ghennady [ 20/Jul/12 ]

Hi. Thanks for the quick response.

I looked at the changes, and have a question: whether you need to reset the parameters when cloning? Thus broken backward compatibility with versions <2.3.

Comment by Marco Pivetta [ 20/Jul/12 ]

Actually, I just implemented your expected behaviour (see tests), which is compatible with what the `AbstractQuery` does. It can also be done the other way around, waiting for feedback by Benjamin Eberlei

Comment by Marco Pivetta [ 20/Jul/12 ]

Ah, nevermind. You're right. Will change my code





[DDC-1929] [GH-400] Changed commands to use command.name in the help Created: 16/Jul/12  Updated: 03/Nov/13  Resolved: 23/Jul/12

Status: Closed
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: Fixed Votes: 0
Labels: None


 Description   

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

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

Message:

The current code does not work for child classes: it gets the name too early as the child has not changed it yet at this point. using ``%command;name%`` replaces it only when the help needs to be displayed.



 Comments   
Comment by Benjamin Eberlei [ 23/Jul/12 ]

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

Comment by Doctrine Bot [ 03/Nov/13 ]

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





[DDC-1930] [GH-401] Add Doctrine\Tests in composer autoload Created: 17/Jul/12  Updated: 04/Nov/13  Resolved: 17/Jul/12

Status: Closed
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: Invalid Votes: 0
Labels: None


 Description   

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

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

Message:



 Comments   
Comment by Benjamin Eberlei [ 17/Jul/12 ]

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

Comment by Doctrine Bot [ 04/Nov/13 ]

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





[DDC-1919] Doctrine fails to escape entity with reserved name in various situations Created: 10/Jul/12  Updated: 19/Jul/12  Resolved: 11/Jul/12

Status: Closed
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: 2.2
Fix Version/s: 2.3, Git Master
Security Level: All

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

MySQL



 Description   

I have submitted a PR here, fixing part of this issue: https://github.com/doctrine/dbal/pull/166

However, it fails when UPDATE or INSERT is used. I'm using a very simple, and common, entity name: Group. Doctrine is failing to escape this in various situations, causing queries to fail in MySQL due to reserved keywords.



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

Can you try using the quoting strategy in master? By defining an '@Table(name="`Group`")' on your entity you should be able to fix this issue by yourself... Anyway, this is only available in latest master.
Please give it a try and let us know.

Comment by Klaus Silveira [ 11/Jul/12 ]

That hack, of course, fixes the problem. However, Doctrine is failing to escape entities with reserved keywords in various different situations and this should be a major problem, specially since there are many keywords that are common table names. Having to change the table name or escape the table name manually is not the best solution.

I have look through the code but could not find out why getQuotedTableName() is failing to quote the table name "Group". I fixed the other problem, involving schema creation, but this one i couldn't fix. That's why i'm opening the issue, hoping someone with more experience in the ORM codebase manages to fix it.

Comment by Marco Pivetta [ 11/Jul/12 ]

Klaus Silveira, doctrine won't quote (at least with the default strategy) a table called "Group". The default strategy will look for the sorrounding "`" ("`Group`").
Is it still failing to quote something in latest master? Can you write a simple example of a failure you are getting?

Comment by Klaus Silveira [ 11/Jul/12 ]

The failure is caused when querying anything related to an entity wich it's name is a reserved keyword, for example, an entity called "Group". I expected Doctrine to quote such table names.

Comment by Marco Pivetta [ 11/Jul/12 ]

Klaus Silveira did you put an @Table(name="`Group`") in it?

Comment by Marco Pivetta [ 11/Jul/12 ]

Please note that

Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
@Table(name="Group")

and

Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
@Table(name="`Group`")

are quite different. That's why I'm asking

Comment by Klaus Silveira [ 11/Jul/12 ]

As i said, that hack fixes the problem. But i don't believe that having to change the table name or escape the table name manually is the best solution. Doctrine should be doing that transparently, as it does for other situations (such as during schema creation). Why not during all other operations? Makes no sense at all.

Comment by Marco Pivetta [ 11/Jul/12 ]

This is not a hack... In ORM, "`" is not the MySQL identifier quote. It is exactly thought as a character with which you tell the ORM that the identifier should be quoted.
The default strategy does make use of it, so please use it.

Comment by Marco Pivetta [ 11/Jul/12 ]

Also, we won't collect the SQL reserved keywords, nor we can know what keywords are used in all vendors. The patch for the quoting strategy was exactly thought to allow end users to use insecure names for their objects/fields/indexes/etc but without having the ORM implement those checks for them (since it would just be messy and too "magic").

Please also reconsider your pull request on github too ( DBAL-298 ).

I'm closing this one

Comment by Klaus Silveira [ 11/Jul/12 ]

Then what's the purpose of Doctrine\DBAL\Platforms\Keywords\MySQLKeywords?

Comment by Marco Pivetta [ 11/Jul/12 ]

Klaus Silveira not sure, but it isn't used in ORM.

Comment by Benjamin Eberlei [ 19/Jul/12 ]

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





[DDC-1922] [GH-399] Fix phpdocs Created: 11/Jul/12  Updated: 12/Nov/13  Resolved: 11/Jul/12

Status: Closed
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: Fixed Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of Adel-E:

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

Message:



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

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

Comment by Doctrine Bot [ 12/Nov/13 ]

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





[DDC-1915] [GH-396] DDC-1893 - Updating configuration to reflect latest Doctrine Common changes Created: 08/Jul/12  Updated: 02/Nov/13  Resolved: 08/Jul/12

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

Type: Bug Priority: Major
Reporter: Benjamin Eberlei Assignee: Marco Pivetta
Resolution: Fixed 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/396

Message:

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

The `getDefaultAnnotationDriver` method was changes to stop supporting older incompatible Doctrine Common versions in favour of the newer logic.

Also, changing logic so that the SimpleAnnotationReader is no more the
default one. An additional parameter for the method will allow using it (this is a BC break!)

The CS fixes that were additionally implemented (along with other minor changes
that do not affect BC compatibility are caused by a CS sniff via IDE.



 Comments   
Comment by Benjamin Eberlei [ 08/Jul/12 ]

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

Comment by Doctrine Bot [ 02/Nov/13 ]

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





[DDC-1886] [GH-381] [WIP] [DDC-1637] Collection Filtering API Created: 20/Jun/12  Updated: 10/Oct/13  Resolved: 11/Jul/12

Status: Closed
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: Fixed Votes: 0
Labels: None


 Description   

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

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

Message:

This Pull Request implements the new Collection Filtering/Criteria API inside the PErsisters.

Its still heavily WIP and the code is not cleaned up yet. In general i am not yet happy about the problems to get from criteria to SQL, and that is also to complex to use completely internally.

Todo:
1. More tests for Repository impl.
2. Add PersistentCollection impl.
3. Cleanup



 Comments   
Comment by Fabio B. Silva [ 11/Jul/12 ]

Fixed by : https://github.com/doctrine/common/commit/4ac23ae8737fe7b95a7dd0f1346dbd48c7a503b0

Related ticket : http://www.doctrine-project.org/jira/browse/DDC-1637

Comment by Doctrine Bot [ 10/Oct/13 ]

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





[DDC-1900] Impossibility to override built-in SQL functions Created: 30/Jun/12  Updated: 05/Jul/12  Resolved: 05/Jul/12

Status: Closed
Project: Doctrine 2 - ORM
Component/s: DQL
Affects Version/s: Git Master
Fix Version/s: 2.3
Security Level: All

Type: Bug Priority: Major
Reporter: Alex Oroshchuk Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: None
Environment:

Any



 Description   

Doctrine doesn't allow to to create own SQL function for DQL if that function is already defined as "built-in". An example could be custom DATE_ADD implementation.
Method FunctionDeclaration() in Doctrine\ORM\Query\Parser gives higher priority to built-in SQL functions, even if they are not
usable for a specific situation, and registering of own datetime function doesn't help. This issue makes it impossible to use some advanced Doctrine extensions,
for example https://github.com/beberlei/DoctrineExtensions that provide fuller implementations.
Considering the fact that someone may want to use ready components provided by the community, and being new to Doctrine can't figure out the way to hack
or workaround this, the issue is a major one.



 Comments   
Comment by Benjamin Eberlei [ 04/Jul/12 ]

Just name the method differently.

Comment by Alex Oroshchuk [ 05/Jul/12 ]

To rename the method one has to KNOW that he has to rename it, i.e. to know about this issue.
One has to SPEND hours (like me) on understanding that there are built-in implementations and other extensions that are meant
to provide necessary features just don't work. IMHO it's just too cruel to leave it as is.

As to the renaming: is it ok to go and edit source code (change class name at least) provided by someone else and then merge all the sources when new releases appear?
Is that the only way flexible Doctrine provides? Also, I want DQL to be as close as possible to real SQL. I don't want to see weird stuff like MY_DATE_ADD or BETTER_DATE_ADD, or whatever it will be.
Syntax matters, we are all writers, code writers...

I re-open the issue in order to attract more attention, but you are free to decide how to treat it. Hope you'll find the best solution. A short line in documentation could notify about current limitations and save hours for people
who want to be productive with Doctrine.

Comment by Benjamin Eberlei [ 05/Jul/12 ]

Printing statements in bold isnt helpful. This is open-source.

However, you are right that this could be more user-friendly. Its now throwing an exception when an internal function is attempted to be overwritten.





[DDC-1843] CLONE -Join columns can't be quoted Created: 28/May/12  Updated: 15/Aug/12  Resolved: 15/Aug/12

Status: Closed
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.1.6
Fix Version/s: 2.3
Security Level: All

Type: Bug Priority: Major
Reporter: Marc Easen Assignee: Fabio B. Silva
Resolution: Fixed Votes: 0
Labels: None

Attachments: File quoted_joins_fix.diff    

 Description   

Join columns can't be quoted like columns using name="`quoted`". Using annotation driver.

/**
 * @ORM\Table(
 *      name="`category`",
 *      indexes={
 *          @ORM\Index(
 *              name="fk_category_parentId",
 *              columns={"parentId"}
 *          )
 *      },
 *      uniqueConstraints={
 *          @ORM\UniqueConstraint(
 *              name="uq_category_nameParentId",
 *              columns={"name", "parentId"}
 *          )
 *      }
 * )
 */
class Category
{
    /**
     * @ORM\Id
     * @ORM\Column(type="smallint", name="`id`")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="smallint", name="`parentId`", nullable=true)
     */
    protected $parentId;

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

    /**
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="categories")
     * @ORM\JoinColumn(name="parentId", referencedColumnName="id", onDelete="CASCADE", onUpdate="NO ACTION")
     */
    protected $category;
}

... 


public function load(ObjectManager $manager)
    {
        $parent = new Category();
        $parent->setName('parent');
        $manager->persist($parent);
        $manager->flush();

        $child = new Category();
        $child->setName('parent');
        $child->setParentId($parent->getId());
        $child->setCategory($parent);

        $manager->persist($child);
        $manager->flush();
}

Result: Invalid parameter number: number of bound variables does not match number of tokens



 Comments   
Comment by Fabio B. Silva [ 28/May/12 ]

code format

Comment by Fabio B. Silva [ 25/Jun/12 ]

Fixed by : https://github.com/doctrine/doctrine2/commit/cb72219b118c158c9b5344c4b81ff2b1a9149ab0

Comment by Marc Easen [ 05/Jul/12 ]

When inserting into an entity which has quoted columns and unquoted JoinColumn the generated SQL includes the correct number of parameters but the incorrect columns names and bind parameters:

INSERT INTO `table` (`c1`, c1) VALUES (?, ?)

Comment by Marc Easen [ 05/Jul/12 ]

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

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

Hi Marc,

Could you attach your entities or a test case please ?

Thanks

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

Marc, why do you need to quoted columns and unquoted join column ?

For sure duplicated columns is a problem, but your use case does not make sense for me..

Comment by Fabio B. Silva [ 15/Aug/12 ]

More details about the related problem : https://github.com/doctrine/doctrine2/pull/390





[DDC-1818] ResultSetMapping::addJoinedEntityResult does not work Created: 10/May/12  Updated: 17/Jul/12  Resolved: 17/Jul/12

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

Type: Bug Priority: Major
Reporter: Nikola Petkanski Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: None


 Description   

I'm trying to fetch the data for oneToMany relation, but it failed:

Notice: Undefined index: SomeCompany\SomeBundle\Entity\SomeJoinedEntity in ..../symfony/vendor/doctrine/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php line 382

While trying to debug the issue I came to the conclusion that if I use the FQDN entity name it works, but if using SomeBundle:SomeJoinedEntity does not. I also checked the unit tests and I wasn't able to find which test this behavior - they all use the FQDN and not the short name of the entity.

I wasn't sure whether this should be a Symfony 2.0.13 issue or a Doctrine2 one, but in the end I've the intention that it has to be posted here.



 Comments   
Comment by