[DDC-3893] Update statement on bool field with equal expression Created: 04/Sep/15  Updated: 04/Sep/15

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

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


 Description   

Want to run an update statement based on a expression.

e.g.: active specific `uc` and deactivate all others

Code:

{{
$queryBuilder = $this->getEntityManager()->createQueryBuilder();
$queryBuilder->update('TestBUndle', 'uc')
->set('uc.active', '(uc.collection = :collectionId)')
->where('uc.user = :userId');

$queryBuilder->setParameter('collectionId', $collectionId);
$queryBuilder->setParameter('userId', $userId);

$query = $queryBuilder->getQuery();
}}

DQL I get ($query->getDql()):

{{
UPDATE TestBundle:UserCollection uc
SET uc.active = (uc.collection = :collectionId) WHERE uc.user = :userId
}}

Error I get when run $query->getSql():

{{
[Syntax Error] line 0, col 81: Error: Expected
Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got '='
}}

SQL I want:

UPDATE user_collections AS uc SET uc.active = (uc.idCollections = 1) WHERE uc.idUsers = 74






[DDC-3885] Order by on ToMany collections with fetch=“EAGER” doesn't work Created: 02/Sep/15  Updated: 02/Sep/15

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

Type: Bug Priority: Major
Reporter: Amarjeet Singh Rai Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: mapping, orm


 Description   

When using order by on ToMany collections with fetch="EAGER", order by isn't taken into account.

It works when you remove the EAGER fetch.

e.g. doesn't work:
<one-to-many target-entity="TopTenItem" mapped-by="list" field="items" fetch="EAGER">
<order-by>
<order-by-field name="position" direction="DESC"/>
</order-by>
</one-to-many>






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

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

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

php 5.6, mysql 5.7, symfony 2.7



 Description   

When updating the schema I get this:

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

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

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

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



 Comments   
Comment by Cliff Odijk [ 03/Sep/15 ]

We also have the same problem using JOINED table inheritance when i changes the the values to protected i'm not getting this error.





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

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

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

php 5.6, mysql 5.7, symfony 2.7



 Description   

When updating the schema I get this:

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

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

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

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



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

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

Comment by Geert Eltink [ 05/Aug/15 ]

See #DDC-3867





[DDC-3839] EventListener not called when clearing a ManyToMany collection by reference Created: 20/Jul/15  Updated: 01/Sep/15

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

Type: Bug Priority: Minor
Reporter: Jonathan Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: event, many-to-many

Attachments: File ManyToManyEventTest.php    

 Description   

I have an issue with a ManyToMany relation. I don't know if it is a bug or the normal behaviour but when I clear a ManyToMany relation of an entity with the following code :

$user->getGroups()->clear();

the event listener linked to my entity is not called when I flush the entity manager.

I have updated the test \Doctrine\Tests\ORM\Functional\ManyToManyEventTest in order to reproduce the issue (see file attached).



 Comments   
Comment by Jonathan [ 01/Sep/15 ]

Hi, any news about that? Is it an issue or a misunderstanding of how it should work?





[DDC-3832] readOnly should be renamed to immutable in the mapping Created: 16/Jul/15  Updated: 16/Jul/15

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

Type: Improvement Priority: Minor
Reporter: Christophe Coevoet Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: None


 Description   

readOnly in the mapping is currently very confusing. Some people are using it to map entities to views, and then complain about SchemaTool-based projects (migrations for instance) because it handles things as table.
But this is not the actual meaning of this mapping flag. Read-only entities can be inserted and deleted. The only forbidden action on them are updates. This makes the naming totally unsuited.

For reference, Hibernate uses "mutable=false" for the feature corresponding to our "readOnly=true".






[DDC-3825] simple_array slush with empty array Created: 14/Jul/15  Updated: 27/Jul/15

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

Type: Bug Priority: Minor
Reporter: Damian Dlugosz Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: dbal


 Description   

I'm using "doctrine/orm": v2.5.0 and have simple_array type.
If I persist the class where the property with type simple_array is empty array() the query fails.

I'm coming with solution, please see the github PR https://github.com/doctrine/dbal/pull/877



 Comments   
Comment by Damian Dlugosz [ 27/Jul/15 ]

I've mapped the field as nullable=false, so it should never be null.
If you cannot merge this quickly, you should at least add an warning in the docs saying that the field must be mapped set as nullable.





[DDC-3817] hydrating many-to-many relation crashes, when trying to access auto created adder with collection (instead of single entity) Created: 10/Jul/15  Updated: 21/Aug/15  Resolved: 21/Aug/15

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

Type: Bug Priority: Minor
Reporter: Stefan T. Assignee: Steve Müller
Resolution: Duplicate Votes: 0
Labels: AllowRemoveByValue, ArrayCollection, DoctrineModule, EntityGenerator, Hydrator, ORM, Stdlib, Strategy, Tools, add, generateEntityStubMethods, hydrate, remove, to-many
Environment:

doctrine-module 0.8.1
zend-framework 2.5.1
PHP 5.5.12
Apache 2.4.9 (Win64)
WampServer 2.5



 Description   

my concern

IF Doctrine\ORM\Tools\EntityGenerator::generateEntityStubMethods (auto) generates adder, which will expect the parameter to be target entity

WHY would DoctrineModule\Stdlib\Hydrator\Strategy\AllowRemoveByValue::hydrate call this very same adder, passing an ArrayCollection

auto generated code:

abstract entity
public function addAnotherEntity(\NameSpace\Entity\AnotherEntity $xy)
{
    $this->anotherEntity[] = $xy;
}

outline of a (quick) workaround:

abstract entity
public function addAnotherEntity($xy)
{
    if($xy instanceof \NameSpace\Entity\AnotherEntity)
        $this->anotherEntity[] = $xy;
    if($xy instanceof \Doctrine\Common\Collections\ArrayCollection)
        foreach($xy as $entity)
            $this->anotherEntity[] = $entity;
}

(Same goes for removing elements from any "to-many"-collection.)

my question\s

Did I miss something on my way?
Is there any way to "enable" some kind of "multi-adding"?
Is there any chance to (further) influence that adding-part with my xml declaration?

Any advice is very welcome.

Maybe I could write my own EntityGenerator. Maybe I should use a custom Hydrator. But right now it seems to me like a little inconsistency in the library.



 Comments   
Comment by Stefan T. [ 10/Jul/15 ]

created twice (maybe a subconscious double click)

Comment by Stefan T. [ 21/Aug/15 ]

I accidently set the reolution to duplicate, which might have cause that the remaining issue is no longer open (but I'm not quite shure)..

Comment by Stefan T. [ 21/Aug/15 ]

.. my fault.. I was wondering if "resolving as duplicate" might be the right way to close duplicate issues.. but it seems so





[DDC-3816] hydrating many-to-many relation crashes, when trying to access auto created adder with collection (instead of single entity) Created: 10/Jul/15  Updated: 10/Jul/15

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

Type: Bug Priority: Minor
Reporter: Stefan T. Assignee: Steve Müller
Resolution: Unresolved Votes: 0
Labels: AllowRemoveByValue, ArrayCollection, DoctrineModule, EntityGenerator, Hydrator, ORM, Stdlib, Strategy, Tools, add, generateEntityStubMethods, hydrate, remove, to-many
Environment:

doctrine-module 0.8.1
zend-framework 2.5.1
PHP 5.5.12
Apache 2.4.9 (Win64)
WampServer 2.5



 Description   

my concern

IF Doctrine\ORM\Tools\EntityGenerator::generateEntityStubMethods (auto) generates adder, which will expect the parameter to be target entity

WHY would DoctrineModule\Stdlib\Hydrator\Strategy\AllowRemoveByValue::hydrate call this very same adder, passing an ArrayCollection

auto generated code:

abstract entity
public function addAnotherEntity(\NameSpace\Entity\AnotherEntity $xy)
{
    $this->anotherEntity[] = $xy;
}

outline of a (quick) workaround:

abstract entity
public function addAnotherEntity($xy)
{
    if($xy instanceof \NameSpace\Entity\AnotherEntity)
        $this->anotherEntity[] = $xy;
    if($xy instanceof \Doctrine\Common\Collections\ArrayCollection)
        foreach($xy as $entity)
            $this->anotherEntity[] = $entity;
}

(Same goes for removing elements from any "to-many"-collection.)

my question\s

Did I miss something on my way?
Is there any way to "enable" some kind of "multi-adding"?
Is there any chance to (further) influence that adding-part with my xml declaration?

Any advice is very welcome.

Maybe I could write my own EntityGenerator. Maybe I should use a custom Hydrator. But right now it seems to me like a little inconsistency in the library.






[DDC-3806] Add example on how to connect listener to entity implementing NotifyPropertyChanged Created: 02/Jul/15  Updated: 02/Jul/15

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

Type: Documentation Priority: Minor
Reporter: Wouter Wiltenburg Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: event, listener


 Description   

I am implementing the notify `ChangeTracking` policy according to:

http://doctrine-orm.readthedocs.org/en/latest/cookbook/implementing-the-notify-changetracking-policy.html

And chapter 17.3. Notify:

http://doctrine-orm.readthedocs.org/en/latest/reference/change-tracking-policies.html#notify

But an example on where to best connect the listener to the entity implementing the NotifyPropertyChanged interface is missing. It would be great to add some best practices on how and where to add the listeners.






[DDC-3799] Unexpected outcome when using prePersist event and ID GeneratedValue strategy is set to NONE Created: 29/Jun/15  Updated: 29/Jun/15

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

Type: Documentation Priority: Minor
Reporter: yanick Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Setup: I have an entity that uses natural ids (GeneratedValue strategy is set to none). The entity also has life cycle callbacks for prePersist and preUpdate.

Expectation: The UnitOfWork would throw an EntityNotFoundException if I attempt to merge an untracked entity that does not exist in the database. I can catch the exception and call persist. All life cycle callbacks would be executed.

Outcome: No exception is thrown. The UOW creates a new instance of the the incoming object using only the ID. Persist is called on the newly created object and prePersist executes against the empty object. Finally the incoming entity is merged, which overwrites any properties that are managed by prePersist.

I was able to work around this by setting the GeneratedValue strategy to "Custom" and CustomIDGenerator to the AssignedGenerator.






[DDC-3798] Allow Collections to be used transparently with Array-Types Created: 29/Jun/15  Updated: 29/Jun/15

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

Type: Improvement Priority: Minor
Reporter: Robert Schönthal Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: orm


 Description   

Currently its not possible to use Collection with Array-Types transparently:

Entity.php
Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
class Entity
{
    /**
     * @var string[]|Collection
     *
     * @ORM\Column(type="json_array")
     */
    private $aliases = [];

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

if i add Values to the Collection and persist the Entity the aliases are empty.
I need Lifecycle Listener which converts between ArrayCollection and array like this:

Entity.php
Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
    /**
     * @ORM\PrePersist
     */
    public function prePersist()
    {
        $this->aliases = $this->aliases->toArray();
    }

it would be good to have an automatic conversion! Should be fairly easy, i could write a PR if your interessted in...or am i missing a hidden piece?






[DDC-3792] Broken link to api docs in documentation Created: 24/Jun/15  Updated: 24/Jun/15

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

Type: Documentation Priority: Trivial
Reporter: Felipe Figueroa Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: documentation
Environment:

Online documentation



 Description   

Links to API docs from doctrine documentation are broken in its latest version.

For example, in second level cache section, under cache region the link to API Doc points to http://www.doctrine-project.org/api/orm/2.5/class-Doctrine.ORM.Cache.Region.html/ which doesn't exist.

Actually, it doesn't seem to be an API doc section for version 2.5 whatsoever.






[DDC-3767] orm-alternative connection to use different database is working fine but then I have to use orm-default as a driver and not orm-alternative as driver while it should have been the other way. Created: 12/Jun/15  Updated: 12/Jun/15

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

Type: Bug Priority: Major
Reporter: Ovi Mughal Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: mapping
Environment:

Windows 7, Doctrine-ORM-Module 0.9, ZF2 2.5



 Description   

I needed to create module level database connection, I did override to orm-default and created orm-alternative connection but when using driver for it as orm-alternative, object manager instance is not created but when I use orm-default as driver everything works fine. But why?

Here is what is my config:
NOTE: if change orm_oz_default to orm-default on line #25, everything works fine.

return array(
1. 'doctrine' => array(
2. 'connection' => array(
3. 'orm_oz_default' => array(
4. 'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
5. 'params' => array(
6. 'host' => 'localhost',
7. 'port' => '3306',
8. 'user' => 'root',
9. 'password' => '',
10. 'dbname' => 'zfdocttwo',
11. )
12. )
13. ),
14. 'entitymanager' => array(
15. 'orm_oz_default' => array(
16. 'connection' => 'orm_oz_default',
17. )
18. ),
19. 'driver' => array(
20. 'moduletwo_Entity' => array(
21. 'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
22. 'cache' => 'array',
23. 'paths' => array(_DIR_.'/../src/Moduletwo/Entity')
24. ),
25. 'orm_oz_default' => array(
26. 'drivers' => array(
27. 'Moduletwo\Entity' => 'moduletwo_Entity'
28. )
28. )
30. )
31. ),
32.);






[DDC-3764] MappingException thrown on table not in filter Created: 11/Jun/15  Updated: 12/Jun/15

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

Type: Bug Priority: Minor
Reporter: Jordan Gigov Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: import, mapping, postgresql


 Description   

I'm using the command line to import the database schema from en existing project in another language, however this happens every time

jordan@jordan:~/workspace/testimport$ app/console -v doctrine:mapping:import OldBundle --filter=Users

  [Doctrine\ORM\Mapping\MappingException]
  It is not possible to map entity 'QrtzTriggers' with a composite primary key as part of the primary key of another entity 'QrtzCronTriggers#schedName'.
  

As maybe you can see I've specified a filter to only give me one table, but it throws an exception on a completely unrelated one. There are absolutely no database relations between the Qrtz tables and everything else. The only workaround is to drop the tables, just so I can do the import, but that means I'll have to restore the database later. Those tables are for a distinct module within our system, which can't be ported, even if we decide to migrate.

Whatever analyser you're calling in there should really respect the filters. Not only is it doing extra work, but it's also causing this crash.



 Comments   
Comment by Marco Pivetta [ 11/Jun/15 ]

Loading invalid mappings, regardless of how they are filtered afterwards, is still invalid.

Comment by Jordan Gigov [ 12/Jun/15 ]

Invalid? Tell that to the people at Postgre and Quartz. I'm sure they'll agree you can't possibly have an entity with a composite primary key be referenced by others.

Anyway I'm not asking for composite key references to be implemented (I could try doing it once I get familiar with the system), I'm asking that the filter be respected.

Comment by Marco Pivetta [ 12/Jun/15 ]

Invalid? Tell that to the people at Postgre and Quartz.

Well, the ORM, like any other tool, has its limits.

The filtering happens post-load, so your suggestion would require a massive rewrite of the entire functionality.

You could also simply dump the relevant schema and drop the tables from the dump, as you suggested above.





[DDC-3761] Entity Cache Key save bug Created: 08/Jun/15  Updated: 14/Jun/15

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

Type: Bug Priority: Major
Reporter: Mark Assignee: Fabio B. Silva
Resolution: Unresolved Votes: 0
Labels: None


 Description   

When using memcached for caching query or entities, queries will be performed each time, since EntityCacheKey use space in its key. I can submit PR if needed. Let me know if it is needed to be fixed in other places, however i looked through the code and have not found any other places



 Comments   
Comment by Mark [ 10/Jun/15 ]

any news on this one? Should i submit PR or is there any internals issues?

Comment by Fabio B. Silva [ 10/Jun/15 ]

That seems to be the issue,
Please fell free to send a PR

Comment by Mark [ 14/Jun/15 ]

fixed it with simple replacing spaces to dots, in this PR https://github.com/doctrine/doctrine2/pull/1423. We already use this in production with Second Level Cache, however we replaced whole key with md5() for simplicity. Also it may not be question for you but why there is no checks for key length for cache? Since default policy for SCL is to rely on namespaces when generate keys it can easily go out of 250 bytes for memcached, since it invoke a lot of prefixing and so on.

Comment by Mark [ 14/Jun/15 ]

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





[DDC-3753] ManyToMany Relations from Value objects Created: 03/Jun/15  Updated: 03/Jun/15  Resolved: 03/Jun/15

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

Type: Bug Priority: Minor
Reporter: Maximilian Bosch Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: mapping, mysql, orm
Environment:

Ubuntu 14.04 (Virtualbox)/PHP 5.5.25/MySQL 5.5.43


Attachments: PNG File doctrine-user.PNG     PNG File doctrine-userdetails.PNG     PNG File doctrine-vm.PNG    

 Description   

I was trying to setup a many-to-many and a one-to-one relation from an embeddable object, but doctrine ignores these relation columns/tables (see screenshots).
As you can see, I've created a relation for followers called SEN_Following and SEN_UserToRole, but when reviewing the tables on the mysql, these tables are not shown.

When executing "php app/console doctrine:schema:update" I get the following message:
Nothing to update - your database is already in sync with the current entity metadata.



 Comments   
Comment by Maximilian Bosch [ 03/Jun/15 ]

in order to review the whole code, I've pushed to a remote feature branch on github: https://github.com/Ma27/SenNetwork/tree/SenNetwork-108

Comment by Marco Pivetta [ 03/Jun/15 ]

Value Objects should not reference entities in any case.

Comment by Maximilian Bosch [ 03/Jun/15 ]

ok thanks.

but just out of interest: why shouldn't they do??

Comment by Marco Pivetta [ 03/Jun/15 ]

Maximilian Bosch a value object can be compared with another value object by its value, whereas an entity is compared via identifier.

If you include an entity inside your VO you are comparing also the entity state (which is not comparable except for the identifier), and that breaks the entire idea of VO.

VOs should only reference other VOs and primitive types.

Comment by Maximilian Bosch [ 03/Jun/15 ]

Marco Pivetta thank you for your explanation.
but is there a way, how to persist collections inside a value objects??

serialization is IMHO a bad idea. For example I'd like to create a list which shows all users having a specific role, I had to load all users and the UserDetail object and check if they have the value object. With another table I could write a query for that.

Comment by Marco Pivetta [ 03/Jun/15 ]

but is there a way, how to persist collections inside a value objects??

currently not, and I'd still suggest serialization as a fallback (serialization is usually supported by VOs)

Comment by Maximilian Bosch [ 03/Jun/15 ]

Marco Pivetta ok thank you for your help.

I think the simplest solution is moving these relations into the entity and waiting for that feature.
The problem I'll ran into with serialization is that it's virtually impossible to query against a serialized string





[DDC-3735] Problem with Collate Created: 13/May/15  Updated: 13/May/15

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

Type: Bug Priority: Major
Reporter: Hugo Henrique Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: dbal, mapping, mysql, schematool
Environment:

development



 Description   

I'm using Migrations and always when a new version changes in my schema in action `up` SQL removes the definition of the table COLLATE for example:

Version20150513194922.php
public function up(Schema $schema)
{
    $this->addSql('ALTER TABLE customer CHANGE user_id user_id CHAR(36) DEFAULT NULL COMMENT \'(DC2Type: guid)\'');
}

public function down(Schema $schema)
{
    $this->addSql('ALTER TABLE customer CHANGE user_id user_id CHAR(36) NULL DEFAULT COLLATE utf8_unicode_ci COMMENT \'(DC2Type: guid)\'');
}
User.php
/**
 * @ORM\Table(name="user")
 * @ORM\HasLifecycleCallbacks
 */
class User
{
    /**
     * @ORM\Id
     * @ORM\Column(type="guid", options={"unsigned"=true})
     * @ORM\GeneratedValue(strategy="UUID")
     */
    protected $id;

Customer.php
/**
 * @ORM\Entity
 * @ORM\Table(name="customer")
 */
class Customer
{
    /**
     * @ORM\Id
     * @ORM\Column(type="bigint", options={"unsigned"=true})
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\OneToOne(targetEntity="User")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    protected $user;

schema.sql
CREATE TABLE `user` (
  `id` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT '(DC2Type:guid)',
  `name` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
  `username` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
  `username_canonical` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `email_canonical` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `salt` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
  UNIQUE KEY `UNIQ_8D93D649E7927C74` (`email`),
  UNIQUE KEY `UNIQ_8D93D649F85E0677` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `customer` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '(DC2Type:guid)',
  `gender` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `zipcode` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `birthday` date DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `UNIQ_705B3727A76ED395` (`user_id`),
  CONSTRAINT `FK_705B3727A76ED395` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;





[DDC-3719] Criteria won't work on non-owning side of many to many collection Created: 29/Apr/15  Updated: 03/May/15

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

Type: Bug Priority: Major
Reporter: Logan Bailey Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 2
Labels: many-to-many, orm

Issue Links:
Reference
is referenced by DDC-3723 [GH-1399] Fix for DDC-3719. Open

 Description   

I received the following error when trying to call matching on a ManyToMany relationship from the non-owning side.

ErrorException in ManyToManyPersister.php line 234: Undefined index: relationToSourceKeyColumns

ManyToManyPersister::loadCriteria relies on the relationToSourceKeyColumns data from the mapping data. This value is set in ClassMetadataInfo::_validateAndCompleteManyToManyMapping, but it's only set on the owning side of the relationship.






[DDC-3707] Getting Started contains a broken link Created: 21/Apr/15  Updated: 21/Apr/15

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

Type: Documentation Priority: Minor
Reporter: Chris Smith Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: 404, documentation


 Description   

The reference to Zend DB is broken in the getting started documentation.



 Comments   
Comment by Chris Smith [ 21/Apr/15 ]

I think it should point to here: http://framework.zend.com/manual/1.12/en/zend.db.table.html





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

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

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


 Description   

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

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

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

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






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

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

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


 Description   

Hi,

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

Can I currently do this?

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



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

.

Not an issue

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

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

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





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

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

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


 Description   

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

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

I'm trying to map the view as follow:

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

But any time I run this code on it:

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

I got this result:

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

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

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

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



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

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





[DDC-3527] Provide a method to retrieve exactly one entity out of entity repository Created: 20/Jan/15  Updated: 22/Jan/15

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

Type: Improvement Priority: Minor
Reporter: Dominik D Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Hello,

currently we have EntityRepository::findOneBy() method for retrieving a single or none entities out of an EntityRepository. It would be very useful, if there was a method which retrieves exactly one entity or throws NonUniqueResultException in case of multiple records returned or NoResultException in case of zero results returned (just like Query::getSingleResult() currently does).

Very often I find myself creating custom repositories for a couple of ::findOneByOrThrow() methods only. Needless to say it's quite mundane to do. The bodies of such methods follows the same pattern:

1. Query the EntityRepository using EntityRepository::findOneBy().
2. If the result is null, then throw an Exception.
3. Return the result.

It'd be very nice to have it out-of-the-box in the base EntityRepository.

Thanks.



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

We actually want to reduce the repository API, not expand it...

Comment by Dominik D [ 21/Jan/15 ]

Wow, ok. I guess you've got good reasons for it and I shouldn't try to convince you, that having methods for most common use cases out of the box is quite convenient?

If yes, then fine. I can create a common EntityRepository subclass for myself and put any helper methods I want there. This would at least cut down on the code duplication in my codebase.

If what you say is final, then we can close this ticket.

Cheers.

Comment by Marco Pivetta [ 22/Jan/15 ]

I guess you've got good reasons for it and I shouldn't try to convince you, that having methods for most common use cases out of the box is quite convenient?

The main problem is that adding API methods to repositories forces any subclasses to also apply eventual filtering logic to those as well.

Other than that, it's merely a question of interface segregation: the current API is hardly maintainable if we assume that many developers subclassed the EntityRepository class, therefore we should keep it locked until 3.x.

I'll actually mark this issue for 3.0 and defer discussion till then.

Comment by Dominik D [ 22/Jan/15 ]

Ok, thanks.





[DDC-3459] double inversed-by leads to incomprehensible error message Created: 20/Dec/14  Updated: 20/Dec/14

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

Type: Improvement Priority: Minor
Reporter: Tom Vogt Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

When mapping a many-to-one relationship (in XML format), I made the mistake of having both sides be inversed-by (instead of one using mapped-by). This resulted in the following error message on doctrine:schema:update

Doctrine\ORM\ORMException: This behaviour is (currently) not supported by Doctrine 2 (uncaught exception) at /Volumes/User Data/Users/Tom/Sites/BM2/vendor/doctrine/orm/lib/Doctrine/ORM/ORMException.php line 217 while running console command `doctrine:schema:update`

This message could be more helpful. It doesn't tell me where the error is nor what the error is.






[DDC-3450] Embeddables containing only nested embeddables are not hydrated properly Created: 16/Dec/14  Updated: 16/Dec/14

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

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


 Description   

I have the following object mapping:

Location (entity)

  • name <string>
  • bounds <Bounds>

Bounds (embeddable)

  • northeast <Coords>
  • southwest <Coords>

Coords (embeddable)

  • latitude <float>
  • longitude <float>

This setup works fine when persisting entities, the database schema is correct, etc. but when I fetch my `Location` entity afterwards the `bounds` property is wrong. It looks something like this. Calling `getBounds()` on `Location` returns something like:

Coords

  • latitude <float>
  • longitude <float>
  • northeast <Coords>
  • southwest <Coords>

As if the `Coords` embeddable has been transposed with the `Bounds` embeddable.

If I add another property to `Bounds` that isn't an embeddable (say a string) then it's hydrated correctly.



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

James Moss could you come up with a small test case in https://github.com/doctrine/doctrine2/tree/v2.4.7/tests/Doctrine/Tests/ORM/Functional/Ticket ?





[DDC-3449] Single scalar Result and Hidden field Created: 15/Dec/14  Updated: 15/Dec/14

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

Type: Bug Priority: Minor
Reporter: Thomas Gallice Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

I have try to get a single scalar result but my query contains a HIDDEN field. The result is the `NonUniqueResultException` exception.






[DDC-3418] Indexes not inherited from mapped superclass Created: 27/Nov/14  Updated: 27/Nov/14  Resolved: 27/Nov/14

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers
Affects Version/s: 2.4.6
Fix Version/s: 2.5

Type: Improvement Priority: Minor
Reporter: Dustin Thomson Assignee: Marco Pivetta
Resolution: Fixed Votes: 0
Labels: ddl, index, inheritance, mappedsuperclass, mapping

Issue Links:
Duplicate
duplicates DDC-3419 [GH-1196] Inherit indexes from mapped... Resolved
Reference
relates to OXM-2 Mapped-superclass, indexes not gathered Open
relates to DDC-3273 EntityGenerator writes @ORM\Table ann... Open

 Description   

Index definitions on mapped super classes are not inherited by their sub-classes.
I realize this makes the definition of the mapped super-class look a bit weird as it requires it to have a @Table element which isn't strictly valid since there is no corresponding table in the database.
However, it would be nice to set indices on the mapped superclass where the fields are actually defined as this increased comprehension and reduces maintenance.



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

Handled in DDC-3419





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

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

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


 Description   

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

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

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

t0.fieldName

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

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

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

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

And $cleanCriteria should be passed to expandParameters.



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

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

Comment by Edouard COLE [ 12/Mar/15 ]

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





[DDC-3407] add possibility to prevent some entitiy methods from being proxied Created: 21/Nov/14  Updated: 21/Nov/14

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

Type: New Feature Priority: Trivial
Reporter: Oliver Hoff Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This is for optimization of lazy loading, when using entity methods that operate only on identifier values.

This issue is partially addressed via:
https://github.com/doctrine/doctrine2/commit/ba38f3e1e9d725224998af9fce42186b5ccb9641

But it makes assumptions about a certain code style, that is for an "id" identifier property the getter is named "getId". but some code styles prefer "getID".

It would be nice to have an annotation like @ORM\SkipProxy (or equivalents for xml/yaml) to mark a method that should not be proxied.



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

I wouldn't implement it that way. I'm actually building something (non-trivial) at https://github.com/Ocramius/ProxyManager/pull/192 and https://github.com/Ocramius/ProxyManager/issues/159, but it will take some time to get there, and also to get doctrine to use that component to generate proxy classes.





[DDC-3396] In Doctrine\ORM\Query\SqlWalker tableAliasMap and tableAliasCountershould be exposed Created: 17/Nov/14  Updated: 17/Nov/14

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

Type: Improvement Priority: Minor
Reporter: Ioan Badila Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: sql-walker


 Description   

I see that Doctrine\ORM\Query\SqlWalker::tableAliasMap and tableAliasCounter are private properties but this doesn't scale well with public Doctrine\ORM\Query\SqlWalker::getSQLTableAlias($tableName, $dqlAlias = '')

public function getSQLTableAlias($tableName, $dqlAlias = '')
{
$tableName .= ($dqlAlias) ? '@[' . $dqlAlias . ']' : '';

if ( ! isset($this->tableAliasMap[$tableName]))

{ $this->tableAliasMap[$tableName] = strtolower(substr($tableName, 0, 1)) . $this->tableAliasCounter++ . '_'; }

return $this->tableAliasMap[$tableName];
}

For me, getSQLTableAlias() is useful in my custom walker but I can't actually use it without exposing tableAliasMap and tableAliasCounter.






[DDC-3393] Cannot extend existing internal functions Created: 17/Nov/14  Updated: 17/Nov/14  Resolved: 17/Nov/14

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

Type: Bug Priority: Minor
Reporter: Rob Spick Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: None


 Description   

On the MySQL platform, i want to use DATE_SUB with more than just DAY and MONTH, so I write a function and give it the identifier of date_sub however this is not allowed?

Why are we not able to extend the functions, surely if we're writing the function we know the platform that we're extending it on and the other platform specific functions will fail at parsing due to an unsupported type.

I don't want to have to prefix my code with MY_DATE_SUB only for an additional type to be supported at a later date, that would just lead to inconsistencies in my code.



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

Overriding DQL functions may have terrible and unforeseen consequences when dealing with any codebase. If you have a specific use-case, use a specific DQL function, but do not try overriding an existing one that may be used in ways that you are not aware of.





[DDC-3386] Multiple Level Discriminator Mapping Created: 11/Nov/14  Updated: 18/Nov/14

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

Type: Bug Priority: Minor
Reporter: Patrick Rose Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: inheritance, mapping, orm
Environment:

Linux, PHP 5.5.9



 Description   

We currently have a situation where we're required to have up to 4 levels of discriminator mappings, and we're finding that Doctrine will insert into our root entity table, and the leaf entity table correctly. However, the tables in between are not being set at all.

The hierarchy is below:

Deal -> EcommerceDeal
Deal -> EcommerceDeal -> ItemSpecific
Deal -> EcommerceDeal -> ItemSpecific -> ItemSpecificScheduled
Deal -> EcommerceDeal -> DealSet -> SetCombo
Deal -> EcommerceDeal -> DealSet -> SetMoreForLess

When inserting an ItemSpecific entity, I found that the Deal and ItemSpecific tables were filled but the EcommerceDeal was not.

There's not much documentation about trees that are slightly more complicated than the Employee, Person, Admin example in the docs so there's a chance I've misunderstood how to build the tables correctly.

Currently we only have one discriminator column on the Deal table. Should we instead be setting up several columns that are nullable and setting new discriminator columns further down the tree?

EDIT: All classes are Class Table Inheritance, in case that is unclear



 Comments   
Comment by Patrick Rose [ 11/Nov/14 ]

The thing that always confuses me while I'm working on this is the fact that I can select from the Database fine. I've got dummy data in each table and Doctrine is clever enough to select all the correct fields from the correct tables so I'm unsure whether I've made a mistake or if Doctrine has a bug.

Comment by Marco Pivetta [ 11/Nov/14 ]

This looks like normal ORM behavior to me, not really requiring any change. What's the reason for inserts on the other tables?

Comment by Patrick Rose [ 12/Nov/14 ]

We have data that's the same across all Ecommerce Deal types (things like the start time, end time etc). I'd expect to be able to set all the values on (say) an ItemSpecific deal and Doctrine to insert the generic data in the EcommerceDeal table.

Comment by Patrick Rose [ 12/Nov/14 ]

It turns out that Doctrine does support this out of the box. A predecessor had overriden the JoinedSubclassPersister with the sole purpose being to comment out the section relating to discriminator columns.

Comment by Patrick Rose [ 12/Nov/14 ]

Problem is with an overridden method not in the Doctrine core.

Comment by Marco Pivetta [ 13/Nov/14 ]

Patrick Rose do you mean that your version (local file) of the JoinedSubclassPersister was monkey-patched?

Comment by Patrick Rose [ 13/Nov/14 ]

Undoing monkey patch does not fully fix issue

Comment by Patrick Rose [ 13/Nov/14 ]

Marco: We'd overridden a whole bunch of classes to do various things, but I've got no idea what those were (these happened at least 6 months before I joined).

The JoinedSubclassPersister was overridden and just commented out two lines

$tableAlias = ($this->class->rootEntityName == $this->class->name) ? $baseTableAlias : $this->getSQLTableAlias($this->class->rootEntityName);
$columnList[] = $tableAlias . '.' . $discrColumn;

From speaking to people, it seems that the point of using that was to allow the discriminator columns to be on the incorrect tables.

However, even with undoing this, I've just tried to create a ComboDeal and it inserted into the root table and the leaf table but none of the other tables. However it looks like ItemSpecific entities are fine. I'll just retry creation of each entity type and get back to you.

Comment by Patrick Rose [ 13/Nov/14 ]

Just finished doing that. I can create EcommerceDeal entities, and ItemSpecific entities and they'll insert into the correct tables (so the EcommerceDeal entity saves into the EcommerceDeal and Deal tables, and the ItemSpecific entity saves into the ItemSpecific, EcommerceDeal and Deal tables).

The rest only insert into the Deal table and the table relating to that class.

Comment by Patrick Rose [ 18/Nov/14 ]

Is there an update on how we can resolve this?

Comment by Patrick Rose [ 18/Nov/14 ]

We've spent a day looking through and trying to work out what seems to be happening and seem to have a resolution.

It appears that the method of getting the parents was only getting those which weren't transient (and thus were entities), which in our case wasn't working since then Doctrine complains about duplicate column definitions. After overriding the getParentClass to allow us to be explicit we got it to work.





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

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

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

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

 Description   

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

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

and its inverse

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

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

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

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

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

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

I also found this on Google:

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

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

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

Is this effectively a bug?



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

Fixed via DDC-3536 and DDC-3537

Comment by Arthur Bodera [ 02/Sep/15 ]

Thanks!





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

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

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

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

 Description   

Hi,

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

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



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

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





[DDC-3333] doctrine:schema:update --complete does not detect old index Created: 02/Oct/14  Updated: 02/Oct/14

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

Type: Bug Priority: Minor
Reporter: Grégoire Paris Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: postgresql, schematool
Environment:

Ubuntu 14.04, PostgreSQL 9.3



 Description   

When changing the name of an index and using the symfony proxy command doctrine:schema:update --complete --dump-sql, the output only shows a CREATE statement. I would expect to also see a DROP statement. Here is what my index definition looks like :

    indexes:
        admin_entity_created_at_index:
            columns: [ createdAt ]





[DDC-3330] Bad Pagination - rows with sorted collection Created: 29/Sep/14  Updated: 16/Jun/15  Resolved: 16/Jun/15

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

Type: Bug Priority: Minor
Reporter: Thomas Lallement Assignee: Bill Schaller
Resolution: Fixed Votes: 0
Labels: paginator, tests
Environment:

Ubuntu 12.04, PHP 5.5.3


Attachments: File DDC3330Test.php    

 Description   

I use the Doctrine Paginator to be able to have a correct pagination with collection.
I followed the documentation here:
http://doctrine-orm.readthedocs.org/en/latest/tutorials/pagination.html

It works well in most cases but there is a problem when ordering on a property of the entity + on an other property of the collection.

See the failing unit test I joined to this ticket.



 Comments   
Comment by Bill Schaller [ 16/Jun/15 ]

Closed PR via manual merge





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

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

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


 Description   

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

Take the following mapping for a Geometry type:

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

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

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

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

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

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

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



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

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

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

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

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

Comment by Paolo Agostinetto [ 01/Feb/15 ]

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

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





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

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

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

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

 Description   

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

```php
/**

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

I get this:
```php
/**

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

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



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

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

Comment by Phansys [ 11/Sep/14 ]

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

Comment by Phansys [ 11/Sep/14 ]

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

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

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

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

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

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

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

Comment by Doctrine Bot [ 12/Sep/14 ]

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

Comment by Doctrine Bot [ 12/Sep/14 ]

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

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

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

Comment by Phansys [ 13/Sep/14 ]

Thanks Steve Müller.

Comment by Doctrine Bot [ 19/Oct/14 ]

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





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

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

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


 Description   

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



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

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

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

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

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

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

Comment by Marco Pivetta [ 13/Sep/14 ]

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





[DDC-3291] Cannot use eq expression for comparison of DateTime Created: 01/Sep/14  Updated: 02/Sep/14

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

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


 Description   

When I use return ArrayCollection::matching() with criteria defined with eq expression like that:

Criteria::create()->where(Criteria::expr()->eq('day', $day))

I get no results since equality operator uses === comparison which will almost always return false for objects. The only way I found to get around this is to use in operator instead

Criteria::create()->where(Criteria::expr()->in('day', array($day)))





[DDC-3289] Better exception description on some mapping errors Created: 31/Aug/14  Updated: 01/Sep/14

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

Type: Improvement Priority: Minor
Reporter: Luciano Mammino Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: mapping, orm, schematool


 Description   

Mapping problems does not always throw very explicit exceptions.

I had this feeling with a very common error:

This behaviour is (currently) not supported by Doctrine 2"

I essentially forgot to add a "mapped-by" attribute in my mappings and, given this generic message, I admit I had to spend a bit of time before being able to spot the mistake.

That's the code that detected the problem and triggered the proper exception.

Doctrine/ORM/Tools/SchemaTool.php
} elseif ($mapping['type'] == ClassMetadata::ONE_TO_MANY && $mapping['isOwningSide']) {
                //... create join table, one-many through join table supported later
                throw ORMException::notSupported();

Within the $mapping variable I see we have a lot of useful information about the problem. Why don't use them to create a very helpful exception message that reports the exact mapped entity and field that raised the error?

IMHO this will grant a better developer experience, especially for doctrine newcomers!



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

Hey Luciano Mammino, could you come up with an exception message that makes sense to you? This kind of improvement is trivial to implement, so it should be quick...

Comment by Luciano Mammino [ 01/Sep/14 ]

Hi Marco Pivetta
I think something like:

One to Many relationships without "mapped-by" attribute are not allowed. (Found in "\Foo\Bar\SomeEntity", field "somefield")

Will be good enough to give developers some clue about where the problem lies. Anyway I'm not sure it covers all the possible cases for this exception and that it is consistent with other error messages within the codebase.





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

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

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

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

 Description   

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

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

The provided classes to extend:

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

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

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

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



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

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

Comment by Christophe Coevoet [ 04/Oct/14 ]

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

Comment by Christophe Coevoet [ 04/Oct/14 ]

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

Comment by Doctrine Bot [ 19/Oct/14 ]

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

Comment by Doctrine Bot [ 15/Jan/15 ]

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





[DDC-3270] abstract class database entity generation Created: 23/Aug/14  Updated: 19/Oct/14  Resolved: 19/Oct/14

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

Type: Bug Priority: Minor
Reporter: Yan Ni Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: mysql, orm
Environment:

WAMP symfony2



 Description   

I create an abstract class A using @ORM annotations, then create class B which is a subclass of class A. When I use these to update the mysql database, however, a table for class A was also generated, which shouldn't have happened(because class A is an abstract class).



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

abstract types in the ORM are called MappedSuperclass}}es. The fact that a class is {{abstract doesn't mean that it has no concrete table representing it.





[DDC-3265] Incorrect Docblock return type in CacheConfiguration Created: 21/Aug/14  Updated: 30/Aug/14

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

Type: Bug Priority: Trivial
Reporter: James Murray Assignee: Steve Müller
Resolution: Unresolved Votes: 0
Labels: None


 Description   

In CacheConfiguation.php line #88 (at the time of writing)

The docblock for the method getRegionsConfiguration specifies the return type of "QueryCacheValidator" however it's actually returning "RegionsConfiguration"



 Comments   
Comment by Steve Müller [ 22/Aug/14 ]

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

Comment by Doctrine Bot [ 30/Aug/14 ]

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

Comment by Doctrine Bot [ 30/Aug/14 ]

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





[DDC-3261] Bad link in 34.3 Advanced Configuration - Connection Options Created: 20/Aug/14  Updated: 19/Oct/14  Resolved: 19/Oct/14

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

Type: Documentation Priority: Minor
Reporter: Matthew Turland Assignee: Marco Pivetta
Resolution: Fixed Votes: 0
Labels: documentation, orm


 Description   

The link to the DBAL section from 34.3 Advanced Configuration - Connection Options results in a 404 HTTP response. This line appears to be responsible.

Link URL as it appears in the current documentation:
http://docs.doctrine-project.org/dbal/2.0/docs/reference/configuration/en






[DDC-3223] Failing test (get id return string type) Created: 22/Jul/14  Updated: 17/Jan/15  Resolved: 17/Jan/15

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

Type: Bug Priority: Minor
Reporter: Thomas Lallement Assignee: Marco Pivetta
Resolution: Fixed Votes: 0
Labels: identifier, lazy-loading, proxy, type
Environment:

Linux Ubuntu 13.10 / PHP 5.5.3 / Mysql 5.5.x


Issue Links:
Dependency
depends on DDC-3387 [GH-1182] #1086 identifier type in pr... Resolved

 Description   

I found an issue in a specific case, when you find a child entity (JOINED) which is linked to another child entity.

If I clone the linked child entity and call getId(), it gives the value as 'string' rather than 'integer'. If I set the property id as public, there is no problem.

If I call getId on the child entity rather than the clone, it gives 'integer' as expected. So it's weird...

See failing test here: https://github.com/doctrine/doctrine2/pull/1086



 Comments   
Comment by Doctrine Bot [ 11/Nov/14 ]

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

Comment by Marco Pivetta [ 17/Jan/15 ]

Handled in DDC-3387





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

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

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

Windows



 Description   

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

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

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

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

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

in "count" method.

If I remove this line, expected result appear.



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

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

Comment by Draeli [ 06/Jul/14 ]

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

{% for %}

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

Comment by Marco Pivetta [ 06/Jul/14 ]

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

Comment by Draeli [ 06/Jul/14 ]

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

Comment by Draeli [ 06/Jul/14 ]

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

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

and in the view

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

As you see something is not expected.

Comment by Marco Pivetta [ 06/Jul/14 ]

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

Comment by Draeli [ 06/Jul/14 ]

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

Comment by Christophe Coevoet [ 07/Jul/14 ]

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

Comment by Draeli [ 08/Jul/14 ]

A really big thank you Christophe It's work





[DDC-3202] Hydration fails with inhereted overload Created: 01/Jul/14  Updated: 01/Jul/14

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

Type: Bug Priority: Minor
Reporter: Evgen Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: hydration
Environment:

mysql



 Description   

When i use single column with different types hydration not work. No error thrown, but in enity fields wrong data:

Class A{
/**

  • @ORM\Column(name="str", type="string")
    */
    protected $value;
    ...
    }

Class B extends A{
/**

  • @ORM\Column(name="str", type="simple_array")
    */
    protected $value;
    ...
    }

column in database created with type tinytext

after query:
SELECT b FROM A;

Entity of class B contain unparsed string in value property, not hydrated as simple_array. But to store B entities i need to parse this strng into array.
in hydrator i see 2 columns str3 and str4 that mapped to "value" propery and to "str" column in database.






[DDC-3201] Add "option" attribute in JoinTable annotation Created: 01/Jul/14  Updated: 01/Jul/14

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

Type: Improvement Priority: Minor
Reporter: Desjardins Jérôme Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Hello,

In my project, i try to use Doctrine 2 with all table in MyISAM because there is an existing project structure.

But when i create Many To Many association, i can't specify the MySQL's engine.

I think this option can be add in @JoinTable

I speak "annotation" (because I use annotations) but I suggest, of course, for all formats

Thanks






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

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

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

Ubuntu 14.04, PHP 5.5.9-1ubuntu4, Symfony 2.5
Ubuntu 15.04, PHP 5.6.4-4ubuntu6.2, Symfony 2.7.3



 Description   

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



 Comments   
Comment by cloozi [ 02/Sep/15 ]

Hi,
I got the same problem on SF 2.7 with doctrine v2.4.8.
Thank you for your help





[DDC-3175] Update documentation for QueryBuilder to give example of using "set()" with parameter Created: 17/Jun/14  Updated: 17/Jun/14

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

Type: Documentation Priority: Minor
Reporter: Max Summe Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

PHP 5.3



 Description   

QueryBuilder->set method uses Expr\Comparison object, which tries to cast values as strings.

When trying to set('updated', new \DateTime) in an update statement, this causes an exception as \DateTime has no __toString method.

Not sure what the fix is - the format for the \DateTime there depends on the platform and ( I think) the type of field.



 Comments   
Comment by Christophe Coevoet [ 17/Jun/14 ]

you should not set a value directly in the DQL query. You should use the query parameters instead.

Comment by Max Summe [ 17/Jun/14 ]

So you're saying it should not be used like this.

$qb = $em->createQueryBuilder();
$qb->update('User', 'u')
->set("u.field", "new value")
->where("u.field = :oldvalue")
->setParameter("oldvalue", "old value");

Instead, it should be:

$qb = $em->createQueryBuilder();
$qb->update('User', 'u')
->set("u.field", ":value")
->where("u.field = :oldvalue")
->setParameter("oldvalue", "old value")
->setParameter("value", "new value");

Is that correct?

If yes, it would be helpful to add an example to the documentation in this page: http://docs.doctrine-project.org/en/latest/reference/query-builder.html





[DDC-3152] Generating methods does not check for existing methods with different case Created: 04/Jun/14  Updated: 06/Jun/14  Resolved: 06/Jun/14

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

Type: Bug Priority: Minor
Reporter: Jacob Walker Assignee: Marco Pivetta
Resolution: Fixed Votes: 0
Labels: orm


 Description   

When I use `orm:generate-entities --generate-methods=true` to add methods to an existing entity (such as when I add new properties) the generator will redeclare methods if my existing entity is using different case. This is a fatal error because PHP method names are treated as case insensitive.

I have not tested this in 2.4.

Here is a minimal example entity before running the generator. Not the case of `getID`

Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
/**
 * @ORM\Entity
 */
class Employee
{
    /**
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

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

And after running the generator

Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
/**
 * @ORM\Entity
 */
class Employee
{
    /**
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

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

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


 Comments   
Comment by Steve Müller [ 05/Jun/14 ]

Hmm yeah it seems the EntityGenerator does not use reflection to determine whether a method/property already exists but instead tokenizes the source file and compares the methods/properties case-sensitive.
I will have a look at it.

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

Patch supplied in PR: https://github.com/doctrine/doctrine2/pull/1049

Comment by Jacob Walker [ 05/Jun/14 ]

Thanks for looking in to this so quickly, Steve.

Comment by Doctrine Bot [ 06/Jun/14 ]

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

Comment by Marco Pivetta [ 06/Jun/14 ]

Merged @ https://github.com/doctrine/doctrine2/commit/d71159c6c57bce5b83f9a2ddbb16ff5a289c30f1





[DDC-3141] Change the type of a column Created: 28/May/14  Updated: 28/May/14  Resolved: 28/May/14

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

Type: Improvement Priority: Minor
Reporter: Mathias STRASSER Assignee: Marco Pivetta
Resolution: Won't Fix Votes: 0
Labels: postgresql
Environment:

All O.S.



 Description   

Is that possible to change the request when we would like to change the type of a column in PostgreSQL via Symfony 2 ?

app/console doctrine:schema:update --force

[Doctrine\DBAL\DBALException]
  An exception occurred while executing 'ALTER TABLE foo ALTER valid TYPE BOOLEAN':  

  SQLSTATE[42804]: Datatype mismatch: 7 ERROR:  column "valid" cannot be cast to type boolean

For resolve this problem I must execute manually this command :

ALTER TABLE foo ALTER valid TYPE BOOLEAN USING valid::BOOLEAN;

I've asked this question to DoctrineBundle, but they redirected to you (https://github.com/doctrine/DoctrineBundle/issues/292)



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

Mathias STRASSER does this happen also when data is not in the table?

To be honest, this exception seems valid to me, as it actually prevents you from applying destructive DDL on your schema.

Comment by Steve Müller [ 28/May/14 ]

I tend to agree with Marco Pivetta. I know of similar issues with other vendors, too and IMO this exception is perfectly valid as you would otherwise risk to loose data integrity. How would you expect a database to do data conversion between non-compatible types? Maybe you can force type conversion for some types but I don't think it is the task of DBAL to handle this. You should handle this manually IMO.

Comment by Mathias STRASSER [ 28/May/14 ]

I understand this prevent but I think if a user asked to apply a schema update, it should be applied or he should get prompted for a confirmation.
It think it's a pity we are forced to manually perform this query if we are sure.

What do you think ?

Comment by Steve Müller [ 28/May/14 ]

Mathias STRASSER I understand your concern. But this is an exception coming from the database server. How would you expect Doctrine to do the data conversion? Maybe in your case when converting to a BOOLEAN column, this could somehow work (even at database level). But how would you for example expect Doctrine to convert a STRING column to INTEGER for example. You just can't do that. Also you have to keep in mind that DBAL is an abstraction layer and thus requires a cross-vendor behaviour that is the same for all. It might be that PostgreSQL can force the conversion of any column type to BOOLEAN but other vendors can't do this natively. You could adopt the scenario to PHP and type casting. It's a similar scenario.

Comment by Marco Pivetta [ 28/May/14 ]

Won't be fixed.

As I've previously noted, this is an engine error that simply avoids a lossy conversion.

The conversion should be forced manually by the person running the schema tool (by manually running the dump command and applying the DDL statements)

Comment by Mathias STRASSER [ 28/May/14 ]

I quite understand.

Thanks for your replies.





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

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

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

Symfony 2.4.3



 Description   

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

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

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

Make.php:

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

Foobar.php

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

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



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

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

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





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

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

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


 Description   

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

For example:

SQL query:

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

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

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

GROUP BY sclr9

Mysql result:

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

And the PHP code (from custom entity repository):

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

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

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

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

Thank.






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

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

Type: Bug Priority: Major
Reporter: Andy hunt Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: hhvm, orm, paginator
Environment:

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



 Description   

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

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

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

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

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



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

I suggest reporting it to the HHVM team as a bug

Comment by Marco Pivetta [ 28/Mar/14 ]

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

Comment by Christophe Coevoet [ 28/Mar/14 ]

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

Comment by Marco Pivetta [ 28/Mar/14 ]

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

Comment by Marco Pivetta [ 18/Aug/14 ]

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





[DDC-3050] between does not support literal in first argument Created: 26/Mar/14  Updated: 26/Mar/14  Resolved: 26/Mar/14

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

Type: Bug Priority: Trivial
Reporter: Ryan Korczykowski Assignee: Marco Pivetta
Resolution: Won't Fix Votes: 0
Labels: None
Environment:

MySQL



 Description   

This may not be a bug since this feature may not be portable.

The following dql results in an error:

select e from Entity e 
where '2011-01-01' BETWEEN e.periodStart AND e.periodEnd

[Syntax Error] line 0, col 263: Error: Expected =, <, <=, <>, >, >=, !=, got 'BETWEEN'

If I replace the date literal with a bound param it will work as expected.



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

We discourage usage of magic constants in DQL, as well as any form of inclusion of parameters in DQL strings via string concatenation.





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

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

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

Ubuntu



 Description   

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

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

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

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

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






[DDC-3027] Embeddables on mapped supper classes Created: 13/Mar/14  Updated: 13/Mar/14

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

Type: Bug Priority: Minor
Reporter: Antoine Hedgecock Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Deb 7.3, php 5.5.10-1~dotdeb



 Description   

If you have a embeddable on a mapped superclass you get the following error

<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping>
    <embeddable name="DealFinder\Core\ValueObject\Coordinates">
        <field name="latitude"  type="float" precision="10" scale="6" nullable="true"/>
        <field name="longitude" type="float" precision="10" scale="6" nullable="true"/>
    </embeddable>
</doctrine-mapping>
Doctrine\ORM\Mapping\MappingException: Duplicate definition of column 'coordinates_latitude' on entity 'DealFinder\Location\Entity\LocationEntity' in a field or discriminator column mapping.

Moving it to the entity mapping resolves the issues but gives you duplicated code.






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

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

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


 Description   

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

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

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

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

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

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

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



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

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

What is the DQL query that is causing the problem?

Comment by Bojidar Hristov [ 22/Feb/14 ]

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

DQL is something like that:

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

(Class2 extends Class3)
Class3 have is_active column.

And following filter:

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

{ return ""; }

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

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

Comment by Marco Pivetta [ 26/Feb/14 ]

There are two possible solutions here:

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

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

Comment by Bojidar Hristov [ 26/Feb/14 ]

Yes. Here is it sample failing test.

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

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

Comment by Benjamin Eberlei [ 23/Mar/14 ]

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

Comment by Bojidar Hristov [ 14/Oct/14 ]

Do you need something more? The bug is status Feedback?





[DDC-2942] CodeIgniter LIbrary Wrapper Created: 30/Jan/14  Updated: 30/Jan/14

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

Type: Documentation Priority: Minor
Reporter: David Barratt Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Hello!

I've created a CodeIgniter Wrapper Library for Doctrine. I believe it works well and is well documented. The library is based on the example found here (http://docs.doctrine-project.org/en/2.0.x/cookbook/integrating-with-codeigniter.html), but is packaged in a nice, easy to install, 3rd-party library.

The library can be found here:
https://github.com/camna/codeigniter-doctrine

Could we replace this page:
http://docs.doctrine-project.org/en/2.0.x/cookbook/integrating-with-codeigniter.html

With a reference to the library?

Thanks!






[DDC-2927] Pass parameters by constructor on load/create new entities Created: 21/Jan/14  Updated: 21/Jan/14

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

Type: Improvement Priority: Minor
Reporter: Jacek Hensoldt Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Unfortunately I found no possibility to pass parameters by constructor on load/create a entity?

I could realize it with live callbacks or through the event manager, but I think it is not a clean solution to configure objects with callbacks or event managers.

Is there a better way?

An example:

Offer-Entity contains a FeastDay-Service and can not exist without the existence of container object (composition). The composition can not be implemented on the database.

class Offer {
	protected $feastDayService = null;

	public function __construct(FeastDayService $service) {
		$this->feastDayService = $service;
	}

	public function isOfferActive($date) {
		if(true === $this->feastDayService->isFeastDay($date) ) {
			return false;
                }
                return true;
        }
}





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

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

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


 Description   

Please consider the following associations:

  A <>--> B <-- C  

A is an "aggregate" type object w/ a OneToMany collection of Bs. This association is set to cascade persist operations.

C has a unidirectional OneToOne association to B as well.

Adding a new B to A's collection and flushing the EntityManager works - B is persisted (persistence by reachability).

However, when also creating a new C and pointing it to the new B, adding C to the EntityManager and then flushing leads to an exception because B is discovered as a new Entity through a relationship not set to cascade persist operations.

Obviously the problem here is that there are two paths through which we can discover new Entities. The UoW currently starts search from newly (explicitly) added Entities first before it walks through collections of already-managed entities.

I am unsure if it is just a documentation issue or a deeper problem?

If the UoW worked the other way round, the same problem would occur if the cascade persist was on the other association.

A solution would probably require the UoW to first collect all offending (new) Entities and the link they were discovered through, but later on remove Entities from this list if they are found through another association with the cascade persist option. The exception must not be thrown unless the whole reachability graph has been traversed.



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

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





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

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

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

debian 6.0.3, php5.3.3, Mysql 5.1.49-3



 Description   

Atomic operations with nontransactional engines (MyISAM)

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

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

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

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

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

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

An example:

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

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

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

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

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

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

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

$em->persist($user);

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

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

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

(sorry for my english - I try my best



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

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

Comment by Jacek Hensoldt [ 11/Jan/14 ]

Hello Steve,

thank you for your answer.

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

I think:

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

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

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

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

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

Comment by Benjamin Eberlei [ 12/Jan/14 ]

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

{"engine": "MyISAM"}

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

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

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

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

Comment by Benjamin Eberlei [ 12/Jan/14 ]

I added MyISAM as known limitation to the documentation:

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





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

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

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

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



 Description   

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}

?>

When i do this, then i get an exception:

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

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

$user->addAddress($address);

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


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

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

The output from sqlLogger looks like this:

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

 

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

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

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

 



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

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





[DDC-2898] SQL-Table Prefixes example produces php notices with ManyToMany-Associations Created: 09/Jan/14  Updated: 09/Jan/14

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

Type: Documentation Priority: Trivial
Reporter: do.ev. Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

source: http://docs.doctrine-project.org/en/latest/cookbook/sql-table-prefixes.html

In class TablePrefix the line ...

if ($mapping['type'] == \Doctrine\ORM\Mapping\ClassMetadataInfo::MANY_TO_MANY) {

should be replaced by ...

if ($mapping['type'] == \Doctrine\ORM\Mapping\ClassMetadataInfo::MANY_TO_MANY && $mapping['isOwningSide']) {






[DDC-2897] SchemaTool->update() deletes all tables that not belongs to the schema Created: 09/Jan/14  Updated: 09/Jan/14

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

Type: Bug Priority: Minor
Reporter: do.ev. Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

linux, apache, mysql, php, only tested with the zf2-doctrine modules



 Description   

$tool = new \Doctrine\ORM\Tools\SchemaTool($em);
$tool->updateSchema($em->getMetadataFactory()->getAllMetadata());

=> all Tables that not belong to the schema are gone. If you use the commandline tool for update, tables that not belong to the schema are not touched.






[DDC-2851] Allow set custom collection initializer at runtime Created: 12/Dec/13  Updated: 12/Dec/13

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

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


 Description   

Use case: Company, Category, CompanyCategory entities. We are loading set of companies and should initialize Company.companyCategories collection with joined categories, which ordered by Company.title.

I cann't do it via Criteria API, it doesn't supports joins. + I should return same PersistentCollection instance (Company.companyCategories used in Symfony2 forms).

Current workaround:

    public function loadCompanyCategoriesCollectionForCompany(Company $company)
    {
        $companyCategories = $this->_em->createQueryBuilder()
            ->select('cc')
            ->from('OloloCompaniesBundle:CompanyCategory', 'cc')
            ->join('cc.category', 'c')
            ->addSelect('c')
            ->orderBy('c.title')
            ->where('cc.company = :company')
            ->setParameter('company', $company)
            ->getQuery()
            ->getResult()
        ;

        $coll = $company->getCompanyCategories();
        foreach ($companyCategories as $companyCategory) { /* @var $coll \Doctrine\ORM\PersistentCollection */
            $coll->hydrateAdd($companyCategory);
        }
        $coll->setInitialized(true);
    }

What would be nice: native API for setting custom initializers.






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

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

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


 Description   

For example, I've got this schema:

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

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

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

ALTER TABLE tbl_company ALTER verified SET  DEFAULT 'false';

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



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

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





[DDC-2842] Leave out discriminator part of Doctrine' generated SQL Created: 06/Dec/13  Updated: 06/Dec/13

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

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


 Description   

Assume the following AbstractPage model:

/*

  • @ORM\Entity
  • @ORM\Table(name="page")
  • @ORM\InheritanceType("SINGLE_TABLE")
  • @ORM\DiscriminatorColumn(name="type", type="string")
  • @ORM\DiscriminatorMap
  • ( { * "page" = "Page", * "link" = "Link" * }

    )
    */

And the following DQL query:

SELECT p FROM \Page\Model\AbstractPage

The generated SQL will be:

SELECT ... FROM page p0_ WHERE p0_.type IN ('page', 'link')

Now to the question: how can I remove the WHERE clause from this query. On more complex queries this part of the WHERE clause makes it not possible to use some indexes that are defined. This can be resolved by adding type to the indexes, but this makes my indexes larger and I feel this is not necessary.

The AbstractPage is the root in the inheritance tree. Thus we are interested in ALL records in the table. Omiting the WHERE part does precisely that.

So the question is: how can I make Doctrine remove this WHERE part where it is not necessary.






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

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

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

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

 Description   

When applying a Criteria to a PersistentCollection that has been hydrated the field names must be camel case, if the collection has not yet been hydrated the field names must be underscore separated.

The github repo linked here contains a simplified testcase for the matrix of hydrated/non-hydrated entities and camel case/underscore separated fields.

https://github.com/ptlis/DoctrineTestcase



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

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

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

Comment by brian ridley [ 20/Aug/14 ]

Hi,

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

Comment by Simon Paridon [ 12/Dec/14 ]

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

Comment by Simon Paridon [ 17/Dec/14 ]

Hi Marco Pivetta, brian ridley,

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

Comment by Florian Preusner [ 26/Dec/14 ]

+1

Comment by Simon Paridon [ 26/Jun/15 ]

My idea to solve this would go like this:

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

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

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





[DDC-2829] Retrieve fieldName from PersistentCollection Created: 30/Nov/13  Updated: 02/Dec/13  Resolved: 02/Dec/13

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

Type: Improvement Priority: Minor
Reporter: Thomas Lallement Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: orm
Environment:

N/A



 Description   

Hi,

I use a custom listener based on the one of Knp DoctrineBehavior: https://github.com/KnpLabs/DoctrineBehaviors/blob/master/src/Knp/DoctrineBehaviors/ORM/Loggable/LoggableListener.php and I would like to use $uow->getScheduledCollectionDeletions() and $uow->getScheduledCollectionUpdates() to add the modifications from manyToMany relations. (like described here: https://groups.google.com/forum/#!topic/doctrine-user/ONDh5H4hMYQ).

So I itereate on the returned array to get a PersistentCollection from which I'm able to call:

$col->getOwner() : to retrieve the owning entity (the entity at the owning side of the association).

$col->getDeleteDiff() : to retrieve the entities that will be removed from the collection.

$col->getInsertDiff() : to retrieve the entities that will be added to the collection.

$col->getSnapshot() : to retrieve the last snapshot.

$col->toArray() : to retrieve the current entities in the collection.

That's good, and I can get all information about the association mapping but I can't retrieve the fieldName.

I think it could be easily added when initializing the PersistentCollection by adding fieldName in the $assoc parameter before to call setOwner() ?

See http://www.doctrine-project.org/api/orm/2.4/source-class-Doctrine.ORM.UnitOfWork.html#_computeChangeSet



 Comments   
Comment by Thomas Lallement [ 02/Dec/13 ]

In fact it's already possible by getting fieldName on after clling $col->getMapping();





[DDC-2754] Composer: "cat doctrine >> doctrine.php doctrine.php.bat" Created: 22/Oct/13  Updated: 22/Oct/13

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

Type: Bug Priority: Minor
Reporter: Dominic Guhl Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: composer, packagist
Environment:

Win7 x64, PHP 5.5.3, Composer v2013-10-21 (triggered via NetBeans 7.4)



 Description   

If one is triggering a Composer update, doctrine file content overwrites doctrine.php content and creates doctrine.php.bat with the same content. Before the update, none of these files were existent.

(The summary of this issue suggests what actually happens, not what has been executed by Composer or me, neither it appears in the logs!)

The reason why I reported here first is that these files are only in your repository, from all repositories I have chosen.

Composer Setup was:

    "require": {
        "php": ">=5.3.3",
        "zendframework/zendframework": "2.2.*",
        
        "doctrine/doctrine-module": "0.8.*@dev",
        "doctrine/doctrine-orm-module": "0.8.*@dev"
        
    }, 

...and few requirements were recursively solved on executing update:

    symfony/console (v2.3.6)
    doctrine/orm (v2.4.0)

My first suggest would be that composer can't handle unsuffixed files on Windows. If you can confirm this instead of a bug in Doctrine 2, the Composer project may gets a line dropped?

Possible workaround could be the renaming of doctrine to doctrine.sh.

Thanks!






[DDC-2744] Inheritance - Empty value for discriminatorColumn in query Created: 16/Oct/13  Updated: 16/Oct/13

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

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


 Description   

Hello, I have an inheritance problem with the following classes

<?php

namespace Proj\Bundle\MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * ClassTop
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Proj\Bundle\MyBundle\Repository\ClassTopRepository")
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="aVal", type="string")
 * @ORM\DiscriminatorMap({ "ValOne" = "ClassSubOne", "ValTwo" = "ClassSubTwo", "ValThree" = "ClassSubThree" })
 * 
 */
class ClassTop
{
    .....
}

class ClassSubOne extends ClassTop
{
    ....
}

class ClassSubTwo extends ClassTop
{
    ....
}

class ClassSubThree extends ClassTop
{
    ....
}

When i call findAll method my query is not correct

$entityManager->getRepository('ProjMyBundle:ClassSubOne')->findAll()

the query builded

SELECT field, field2 FROM CLASSTOP WHERE AVAL IN () 

The value for the discriminator column is not passed

Thanks for your help






[DDC-2730] Natural ordering in QueryBuilder Created: 09/Oct/13  Updated: 17/Oct/13  Resolved: 17/Oct/13

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

Type: Improvement Priority: Minor
Reporter: Sergio Pavón Salamanca Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: None


 Description   

Maybe this is not the best place to ask for a feature supported by doctrine. I apologize if I've chosen wrong channel.
Hi,
I can't find an easy way to do natural text ordering with QueryBuilder. OrderBy lets us order text, but I want to order including accents and other simbols. For instance, if we have this words:
Alabama, Boston, Álamo, Cardiff.
Natural order: Alabama, Álamo, Boston, Cardiff.
But current Doctrine order: Albama, Boston, Cardiff, Álamo.

I know that I can create a custom function or use native query, but I think that natural order often occurs. There are DBMS specific functions like TRANSLATE or REPLACE that can help, but I think that doctrine not support them.

Thank you,
Sergio.



 Comments   
Comment by Marco Pivetta [ 17/Oct/13 ]

This depends on the collation of your DB/Table/Column, not on Doctrine itself.





[DDC-2677] Doctrine\Common\Annotations\Reader::getMethodAnnotations sometimes doesn't return an array Created: 13/Sep/13  Updated: 19/Dec/13

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

Type: Bug Priority: Minor
Reporter: Ángel Guzmán Maeso Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: None


 Description   

Please read https://github.com/schmittjoh/JMSDiExtraBundle/pull/133



 Comments   
Comment by Christophe Coevoet [ 13/Sep/13 ]

Are you using a cached annotation reader ? and if yes, which cache implementation is it ?

Comment by Ángel Guzmán Maeso [ 13/Sep/13 ]

Yes. I am using APC. In my config.yml for production:

<pre>
doctrine:
orm:
metadata_cache_driver: apc
result_cache_driver: apc
query_cache_driver: apc
</pre>

Comment by Christophe Coevoet [ 13/Sep/13 ]

I'm not talking about your ORM cache but about the annotation reader cache (for Symfony, it is configured in FrameworkBundle, and it defaults to a FileCacheReader if you don't configure it explicitly)

Comment by Ángel Guzmán Maeso [ 13/Sep/13 ]

Ok sorry. I am still very new with Symfony and Doctrine.

This is the framework config:
framework:
translator:

{ fallback: en }

secret: %secret%
router:
resource: "%kernel.root_dir%/config/routing.yml"
form: true
csrf_protection: true
validation:

{ enable_annotations: true }

templating:
engines: ['twig']
assets_version: v1.0
default_locale: %locale%
trusted_proxies: ~
session: ~

So it should be FileCacheReader as default config.

PS: I found this that could be related http://stackoverflow.com/questions/14070492/doctrine-annotations-filecachereader-php-invalid-argument

Comment by Jonathan Ingram [ 19/Dec/13 ]

I've noticed this issue since upgrading two things (not sure if either or both are relevant):

1. PHP 5.3 --> 5.5.7
2. Changed to memcached instead of apc for the 3 doctrine ORM cache drivers (note: I haven't touched the framework:annotations:cache configuration so it's the default "file")

I've tried to debug it but no luck figuring out what's going on. As far as I can see, the result is actually an empty array so I am not sure why PHP complains. Makes me wonder if it's a PHP 5.5 bug.

Comment by Marco Pivetta [ 19/Dec/13 ]

Jonathan Ingram can we reduce the scope of the problem? Try using an array cache to remove any caching/serialization related issues.





[DDC-2658] Inserting NULL for Undefined Variables Created: 07/Sep/13  Updated: 07/Sep/13

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

Type: Bug Priority: Minor
Reporter: John Julien Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: default, mysql, null
Environment:

CentOS Linux, VMware, MySQL



 Description   

When a MySQL schema contains a line like this:
`failedattempts` int(11) NOT NULL DEFAULT '0',

If a new entity is created and the failedattempts variable is never set, Doctrine attempts to insert the value NULL which throws an SQL error. If a value is undefined for a new object, shouldn't it just be excluded from the insert fields?






[DDC-2649] Hydration in bidirectional, OneToOne relationship, PK as FK for owning side, is problematic Created: 04/Sep/13  Updated: 04/Sep/13

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

Type: Bug Priority: Major
Reporter: Jérôme Viveret Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: FK, OneToOne, PK, bidirectional


 Description   

I am referring to this situation https://gist.github.com/anonymous/6435032

The following problem occur:

When using HardCover as the root entity of a query, the ObjectHydrator fails to properly register the first [HardCover of the resultset]'s Book. Only the first. The following HardCover have their Books correctly linked. The inverse situation (using Book as the root entity) works fine.

When some other entity (say WoodenPart) is linked to HardCover via a ManyToOne association, using WoodenPart as a query root results in no WoodenPart have their HardCover registered.






[DDC-2644] "final" declaration of ORM\Query class prevents proper unit testing of repositories/models Created: 31/Aug/13  Updated: 31/Aug/13

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

Type: Improvement Priority: Minor
Reporter: Tomáš Lembacher Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: orm
Environment:

all



 Description   

For proper unit testing it is neccesary to mock all the dependencies from tested class. In repositories/models, one of the dependencies is ORM\Query class. Because it is declared as final, it is neccesary (in order to perform at least some unit test) to create fake entity manager and than lot of assertions. This all won't be needed if ORM\Query won't be declared final, mock can be created and no additional work won't be neccessary in order to create better unit test.






[DDC-2633] How i can use arithmetic expression in the ORDER BY clause? Created: 26/Aug/13  Updated: 26/Aug/13

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

Type: Documentation Priority: Trivial
Reporter: Liverbool Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

I found solution in this site: http://michelsalib.com/2012/03/04/doctrine2-ninja-with-the-hidden-keyword/

I want to use:
... ORDER BY DATE_FORMAT(field, '%Y')
or
... ORDER BY CONVERT(field USING [CHARSET])

and it catch exception like:

<br />
<b>Fatal error</b>: Uncaught exception 'Doctrine\ORM\Query\QueryException' with message 'SELECT t.id, t.label, t.id AS value, t.label AS text FROM Entities\Repair\ProductType t WHERE t.bch_id=?1 ORDER BY DATE_FORMAT(t.create_date,'%Y') ASC' in /home/joyprice.core/Vendor/Doctrine/orm/lib/Doctrine/ORM/Query/QueryException.php:39
Stack trace:
#0 /home/joyprice.core/Vendor/Doctrine/orm/lib/Doctrine/ORM/Query/Parser.php(396): Doctrine\ORM\Query\QueryException::dqlError('SELECT t.id, t....')
#1 /home/joyprice.core/Vendor/Doctrine/orm/lib/Doctrine/ORM/Query/Parser.php(744): Doctrine\ORM\Query\Parser->syntaxError('end of string')
#2 /home/joyprice.core/Vendor/Doctrine/orm/lib/Doctrine/ORM/Query/Parser.php(229): Doctrine\ORM\Query\Parser->QueryLanguage()
#3 /home/joyprice.core/Vendor/Doctrine/orm/lib/Doctrine/ORM/Query/Parser.php(304): Doctrine\ORM\Query\Parser->getAST()
#4 /home/joyprice.core/Vendor/Doctrine/orm/lib/Doctrine/ORM/Query.php(233): Doctrine\ORM\Query\Parser->parse()

But have solution from DQL?

Sorry to ask the question in Issues Tracker.
Thanks






[DDC-2632] Doctrine reverse engineer doesn't honor NOT NULL foreign keys Created: 24/Aug/13  Updated: 24/Aug/13

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

Type: Bug Priority: Minor
Reporter: Paolo Avezzano Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: engineer, mysql, null, nullable, reverse, yaml
Environment:

MAMP, latest version. Symfony up to date



 Description   

In this table, the two foreign keys (which I had to downgrade from primary keys because of Doctrine and then added a separate PK named 'Id') called 'Oggetto' and 'Sistema' have been set as NOT NULL.

-- -----------------------------------------------------
-- Table `mydb`.`Composizione`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`Composizione` ;

CREATE  TABLE IF NOT EXISTS `mydb`.`Composizione` (
  `Id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
  `Oggetto` INT UNSIGNED NOT NULL ,
  `Sistema` INT NOT NULL ,
  INDEX `fk_Oggetto_has_Sistema_Sistema1_idx` (`Sistema` ASC) ,
  INDEX `fk_Oggetto_has_Sistema_Oggetto1_idx` (`Oggetto` ASC) ,
  PRIMARY KEY (`Id`) ,
  CONSTRAINT `fk_Oggetto_has_Sistema_Oggetto1`
    FOREIGN KEY (`Oggetto` )
    REFERENCES `mydb`.`Oggetto` (`Id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Oggetto_has_Sistema_Sistema1`
    FOREIGN KEY (`Sistema` )
    REFERENCES `mydb`.`Sistema` (`Id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

Converting into Yaml here it is what I get.

    type: entity
    table: Composizione
    fields:
        id:
            id: true
            type: integer
            unsigned: true
            nullable: false
            column: Id
            generator:
                strategy: IDENTITY
    manyToOne:
        oggetto:
            targetEntity: Oggetto
            cascade:      {  }
            mappedBy:     null
            inversedBy:   null
            joinColumns:
                Oggetto:
                    referencedColumnName: Id
            orphanRemoval: false
        sistema:
            targetEntity: Sistema
            cascade:      {  }
            mappedBy:     null
            inversedBy:   null
            joinColumns:
                Sistema:
                    referencedColumnName: Id
            orphanRemoval: false
    lifecycleCallbacks: {  }

Basically it lost in translation the NOT NULL part.
To make it work I had to manually add two "nullable: false" lines as I did below:

    type: entity
    table: Composizione
    fields:
        id:
            id: true
            type: integer
            unsigned: true
            nullable: false
            column: Id
            generator:
                strategy: IDENTITY
    manyToOne:
        oggetto:
            targetEntity: Oggetto
            cascade:      {  }
            mappedBy:     null
            inversedBy:   null
            joinColumns:
                Oggetto:
                    referencedColumnName: Id
                    nullable:     false
            orphanRemoval: false
        sistema:
            targetEntity: Sistema
            cascade:      {  }
            mappedBy:     null
            inversedBy:   null
            joinColumns:
                Sistema:
                    referencedColumnName: Id
                    nullable:     false
            orphanRemoval: false
    lifecycleCallbacks: {  }

Is it a bug or am I missing something?

Regards,
Paolo Avezzano






[DDC-2595] UoW is not supposed to trigger the post-load event for uninitialized proxies. Created: 06/Aug/13  Updated: 06/Aug/13

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

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


 Description   

When one entity have multiple nested levels and associated to 700+ other entities, the ORM exhausts a large amount of memory and execution time which exceeds either the memory limit or the maximum execution time.

Prerequisite:

1. generate an entity, named "Mr. G", with 4 nested levels of association.
2. ensure that the generated entity associating to 700+ entities.
3. create a post-load event listener which may or may not be restricted to uninitialized proxies.

How to Reproduce:

1. have a code to load the "Mr. G" entity.
X. (Done)

Notes:
The initial investigation indicates that UnitOfWork should not trigger the post-load event for uninitialized proxies.

One thing worth-mentioning is that if the event listener ignores all proxies, we will not have this problem. However, some properties (e.g., ones of type TEXT/BLOB) are not loaded into normal entities but they are loaded into the proxies.






[DDC-2570] Doctrine CLI Tools - Clear All Cache Created: 24/Jul/13  Updated: 17/Jan/15

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM, Tools
Affects Version/s: 2.3.4
Fix Version/s: 2.x

Type: Improvement Priority: Minor
Reporter: Frederick Marcoux Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: Cli, cache, orm


 Description   

It would be nice to be able to clear all cache one shot instead of clearing them one after one...

Like this:

root$ ./doctrine orm:clear-cache:all

Instead of:

root$ ./doctrine orm:clear-cache:metadata
root$ ./doctrine orm:clear-cache:result
root$ ./doctrine orm:clear-cache:query






[DDC-2495] Partial objects not working with STI Created: 10/Jun/13  Updated: 11/Jun/13

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

Type: Bug Priority: Major
Reporter: Radoslaw Ejsmont Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: STI, dql, orm, partial
Environment:

Symfony2 project, Doctrine ORM with MySQL database backend


Attachments: File CrossVial.php     File Entity.php     File InjectionVial.php     File Stock.php     File StockVial.php     File Vial.php    

 Description   

When I try to create a query retrieving partial objects of a root class in single table inheritance hierarchy, the resulting SQL includes all fields from the whole class hierarchy.

DQL:
SELECT partial v.

{id, setupDate, flipDate}

FROM VIB\FliesBundle\Entity\Vial v WHERE v.id IN (1,2,3,4,5,6,7,8,9,10)

SQL:
SELECT v0_.setupDate AS setupDate0, v0_.flipDate AS flipDate1, v0_.id AS id2, v0_.type AS type3, v0_.parent_id AS parent_id4, v0_.position_id AS position_id5, v0_.prevPosition_id AS prevPosition_id6, v0_.incubator_id AS incubator_id7, v0_.stock_id AS stock_id8, v0_.male_id AS male_id9, v0_.virgin_id AS virgin_id10, v0_.targetStock_id AS targetStock_id11, v0_.targetStockVial_id AS targetStockVial_id12 FROM Vial v0_ WHERE (v0_.id IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) AND v0_.type IN ('vial', 'stock', 'cross', 'injection')



 Comments   
Comment by Fabio B. Silva [ 10/Jun/13 ]

Could you please provide your entities ?

Thanks

Comment by Radoslaw Ejsmont [ 11/Jun/13 ]

This is the whole class hierarchy.

Comment by Radoslaw Ejsmont [ 11/Jun/13 ]

I have actually noticed, that the "partial" keyword is ignored even for entities that are not using any inheritance schema. So it seems that this keyword is generally ignored.

Right now the following query:

SELECT e, partial p.

{id}

, o, s FROM VIB\FliesBundle\Entity\StockVial e LEFT JOIN e.parent p LEFT JOIN e.position o LEFT JOIN e.stock s WHERE e.setupDate > :date AND e.trashed = false ORDER BY e.setupDate DESC ORDER BY e.id DESC

would result in the following SQL:

SELECT v0_.setupDate AS setupDate0, v0_.flipDate AS flipDate1, v0_.notes AS notes2, v0_.size AS size3, v0_.labelPrinted AS labelPrinted4, v0_.trashed AS trashed5, v0_.temperature AS temperature6, v0_.id AS id7, v1_.id AS id8, r2_.rackRow AS rackRow9, r2_.rackColumn AS rackColumn10, r2_.id AS id11, s3_.name AS name12, s3_.genotype AS genotype13, s3_.notes AS notes14, s3_.vendor AS vendor15, s3_.infoURL AS infoURL16, s3_.verified AS verified17, s3_.id AS id18, v0_.type AS type19, v0_.parent_id AS parent_id20, v0_.position_id AS position_id21, v0_.prevPosition_id AS prevPosition_id22, v0_.incubator_id AS incubator_id23, v0_.stock_id AS stock_id24, v1_.type AS type25, v1_.parent_id AS parent_id26, v1_.position_id AS position_id27, v1_.prevPosition_id AS prevPosition_id28, v1_.incubator_id AS incubator_id29, v1_.stock_id AS stock_id30, v1_.male_id AS male_id31, v1_.virgin_id AS virgin_id32, v1_.targetStock_id AS targetStock_id33, v1_.targetStockVial_id AS targetStockVial_id34, r2_.rack_id AS rack_id35, s3_.sourceCross_id AS sourceCross_id36 FROM Vial v0_ LEFT JOIN Vial v1_ ON v0_.parent_id = v1_.id AND v1_.type IN ('vial', 'stock', 'cross', 'injection') LEFT JOIN RackPosition r2_ ON v0_.position_id = r2_.id LEFT JOIN Stock s3_ ON v0_.stock_id = s3_.id WHERE (v0_.setupDate > '2013-04-11' AND v0_.trashed = 0) AND v0_.type IN ('stock') ORDER BY v0_.setupDate DESC, v0_.id DESC

Please note that ALL properties of parent have been included in the generated SQL.

You can find the whole project (Symfony2) on github: https://github.com/rejsmont/LabDB

Best,

R.

Comment by Radoslaw Ejsmont [ 11/Jun/13 ]

I have noticed that using the setHint(Doctrine\ORM\Query::HINT_FORCE_PARTIAL_LOAD, 1) forces partial load, however then even the entities I want loaded entirely (with proxied references) are partially loaded (i.e. all the references are forced to null, unless explicitly loaded via join).





[DDC-2489] Missing semicolon in schema update tool, using dump-sql argument Created: 05/Jun/13  Updated: 08/Sep/13  Resolved: 08/Sep/13

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

Type: Bug Priority: Minor
Reporter: Robert-Jan Assignee: Guilherme Blanco
Resolution: Fixed Votes: 0
Labels: Cli, schematool


 Description   

When executing the schema-tool update script, using the --dump-sql argument (e.g. "app/console doctrine:schema:update --dump-sql" in a symfony2 project), the semicolon behind the last query is missing.



 Comments   
Comment by Guilherme Blanco [ 12/Jun/13 ]

Fixed in https://github.com/doctrine/doctrine2/commit/0d834d0bd4015de2c103a03592c1543399f1b363





[DDC-2467] Incorrect work with default values, indexes, autoincrement (patch attached) Created: 23/May/13  Updated: 28/May/13

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

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

Attachments: Text File ORM.patch    

 Description   

If you use in your MySQL database default values, indexes or string primary key, you get incorrect mapping by mapping generator. For get it - just use in database one or more from listed abilities, generate mapping for that and then try to dump-sql with schema-tool:update.

Hope you fix it. Tnx!



 Comments   
Comment by Marco Pivetta [ 23/May/13 ]

Marked as minor improvement - thank you for the patch!

Comment by And [ 28/May/13 ]

When it will be merged? Maybe, planned version?

Comment by Marco Pivetta [ 28/May/13 ]

And such a patch requires failing tests before being applied - that's up to whoever picks it up.

Comment by And [ 28/May/13 ]

So if I add patch with tests - it will be merged? =)

Comment by Marco Pivetta [ 28/May/13 ]

Most probably - you can open a pull request against the current ORM master for that





[DDC-2465] ProxyClass load, and empty ids Created: 21/May/13  Updated: 22/May/13  Resolved: 21/May/13

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

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

Osx



 Description   

If you have lazy association (example many-to-one) that have empty id (for empty i mean empty string and not null) you (correctly) get EntityNotFoundException.

But i'm working with a system that sometimes put an empty string instead of null in fk fields.

So i've add this little snipped of code __load method in $_proxyClassTemplate, ProxyFactory:

// GT, 2013-05-21 If all identifier are empty you not need to try load

        if (is_array($this->_identifier)) {
            $isEmpty = true;
            foreach($this->_identifier as $iK => $iV) {
                if (!empty($iV))
                    $isEmpty = false;
            }

            if ($isEmpty)
                return;
        }
        // END GT EDIT


 Comments   
Comment by Marco Pivetta [ 21/May/13 ]

What does `$this->_identifier` contain in your failing case?

Comment by Gabriele Tondi [ 21/May/13 ]

It contains for example

array(
[id] =>
);

Because on db you find an empty string and not a null value.

Comment by Marco Pivetta [ 21/May/13 ]

If I get it correctly, you are using empty strings to emulate NULL references, which is invalid in SQL ( I've explained it extensively at http://stackoverflow.com/questions/15502408/doctrine-2-use-default-0-values-instead-of-null-for-relation/15511715#15511715 )

Is this what you are doing? Because for any identifier that is not NULL an attempt to load it should be run, regardless of its content.

Comment by Gabriele Tondi [ 21/May/13 ]

That's not me

It's the system by which i'm sharing the db.
It uses MyIsam engine with no fk or index, so i've found this way to skip load when on db i've empty strings.

Are there other (maybe cleaner) ways?

Thanks,
Gabriele

Comment by Marco Pivetta [ 21/May/13 ]

No, the only correct way to handle this is to set NULL values for the association meta-columns. Marking as invalid

Comment by Gabriele Tondi [ 21/May/13 ]

I can't find doc about it: https://doctrine-orm.readthedocs.org/en/latest/reference/annotations-reference.html?highlight=column#annref-column

Can you give an example?

Comment by Marco Pivetta [ 21/May/13 ]

`$this->someAssociation = NULL;`. That's basically what I mean.

Comment by Gabriele Tondi [ 22/May/13 ]

Mmm, didn't understand.

Anyway, we've tried to fix the old Delphi Monster witch store empty strings instead of nulls... with no results.

So, here is my workaround, maybe this can be useful for other developers who will be in troubles in the future..

In "UnitOfWork" class, public method "createEntity".

[...]

UnitOfWork.php
 
// TODO: Is this even computed right in all cases of composite keys?
                    foreach ($assoc['targetToSourceKeyColumns'] as $targetColumn => $srcColumn) {
                        $joinColumnValue = isset($data[$srcColumn]) ? $data[$srcColumn] : null;

                        // START-EDIT

                        // GT: our moas store empty string instead of null in fk columns.
                        // So, let's check and handle it as null!

                        if (empty($joinColumnValue))
                            $joinColumnValue = null;

                        // END-EDIT

                        if ($joinColumnValue !== null) {
                            if ($targetClass->containsForeignIdentifier) {
                                $associatedId[$targetClass->getFieldForColumn($targetColumn)] = $joinColumnValue;
                            } else {
                                $associatedId[$targetClass->fieldNames[$targetColumn]] = $joinColumnValue;
                            }
                        }
                    }

[...]

Regards,
Gabriele

Comment by Marco Pivetta [ 22/May/13 ]

Gabriele Tondi the ORM does not deal with such architectures (nor with generally invalid usage of RDBMS systems). The only acceptable solution in ORM is with correct NULL values, as it should be, so this patch is invalid.





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

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

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

Mysql 5.1.66 / Symfony 2.2.1



 Description   

For a parent class:

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

and simple Child1 & Child2 entities.

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

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

Enough for the context.
The symptoms:

$em->remove(instanceOfExternalEntity);

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

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

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



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

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

Comment by Bruno Jacquet [ 06/May/13 ]

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

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

Comment by Bruno Jacquet [ 06/May/13 ]

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

Comment by Bruno Jacquet [ 06/May/13 ]

Maybe using

cascade={"remove"}

, instead of

onDelete="CASCADE"

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

Comment by J [ 25/Apr/14 ]

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





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

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

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


 Description   

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

/**

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

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

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



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

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





[DDC-2407] AbstractExporter _getIdGeneratorTypeString does not know about the UUID generator Created: 20/Apr/13  Updated: 20/Apr/13  Resolved: 20/Apr/13

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

Type: Bug Priority: Minor
Reporter: Jeroen Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: None


 Description   

Shouldn't the AbstractExporter->_getIdGeneratorTypeString() method also know about the UUID generator ?



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

Fixed for 2.4





[DDC-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-2398] Add a "use namespace" like feature to DQL to have short/reusable entity classname Created: 11/Apr/13  Updated: 11/Apr/13  Resolved: 11/Apr/13

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

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


 Description   

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

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

could be :

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

or :

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

And with a default namespace attached to the entity manager :

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



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

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

Comment by David Berlioz [ 11/Apr/13 ]

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

Comment by Marco Pivetta [ 11/Apr/13 ]

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





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

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

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

n/a



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

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

Throws the following exception:

RuntimeException: Unknown comparison operator: CONTAINS

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

-------

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



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

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

Comment by Matthieu Napoli [ 16/Sep/13 ]

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

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

Comment by Doctrine Bot [ 11/Oct/13 ]

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

Comment by Matthias Althaus [ 27/May/14 ]

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

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

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

Running those lib versions:

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

Comment by Marco Pivetta [ 27/May/14 ]

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

Comment by Matthieu Napoli [ 27/May/14 ]

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

Comment by Marco Pivetta [ 27/May/14 ]

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

Comment by Matthieu Napoli [ 27/May/14 ]

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

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

Comment by Marco Pivetta [ 27/May/14 ]

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

Comment by Matthias Althaus [ 03/Jun/14 ]

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





[DDC-2388] Zend Optimizer Plus/opcache have overlap in config settings, annotations reader doesn't identify these properly Created: 04/Apr/13  Updated: 08/Sep/13  Resolved: 20/Apr/13

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

Type: Bug Priority: Minor
Reporter: Ross Cousens Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: None


 Description   

Doctrine\Common\Annotations\AnnotationReader.php

A change was recently authored in the AnnotationReader constructor that checked for a properly configured opcode cache (namely saving comments so that Doctrine can parse annotations).

The current open source version of Zend Optimizer+ hosted at GitHub (https://github.com/zend-dev/ZendOptimizerPlus) when loaded registers itself as a module with the name "Zend Optimizer+" but takes configuration directives in the form of "opcache.<parameter>".

The change to the constructor requires that if the module name is Zend Optimizer+, then the configuration directives must be prefixed with "zend_optimizerplus.<parameter>". This is clearly incorrect.

The most recent update now complains of an AnnotationException as a consequence of this change when running Symfony2 (or Doctrine) with the latest opcache because configuration directives aren't detected properly.

I am happy to fix this but could not find a way to report an issue to initiate the process.

I would suggest something like this in the constructor:

if ((extension_loaded('Zend Optimizer+') || extension_loaded('opcache')) && !(ini_get('opcache.save_comments') == 0 XOR ini_get('zend_optimizerplus.save_comments') == 0)) {

What this means is that if either extension is loaded, one of those directives must be true and configured. This is a compromise. The alternative would be to keep the original source and do the following:

if (extension_loaded('Zend Optimizer+') && ini_get('zend_optimizerplus.save_comments') == 0) {
if (ini_get('opcache.save_comments') == 0)

{ throw AnnotationException::optimizerPlusSaveComments(); }

}

if (extension_loaded('opcache') && ini_get('opcache.save_comments') == 0)

{ throw AnnotationException::optimizerPlusSaveComments(); }

I have no idea about the "opcache" module and what it actually equates to or whether it has alternative formats for its configuration directives. I feel like the second suggestion is even smellier than my original suggestion despite probably handling the edge case better.

If you want a pull request, I will send one, just let me know how you want to handle it.

If my PHP is horrible I apologise.



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

Ross Cousens is this already enstabilished? It's not worth changing it until the ZO+ stuff is stable.

Comment by Ross Cousens [ 15/Apr/13 ]

Marco Pivetta Benjamin Eberlei

Seems stable to me.

I guess whether this is a priority or not depends on your subjective weighting of its importance and whether or not you use ZO+. I've ditched APC, and moved 20+ web servers over to Apache+ZO+. I currently deploy my own version of DBAL commons because it is not possible to work around it.

https://github.com/zend-dev/ZendOptimizerPlus

Please see this reference, why would they suddenly change the name of all the configuration directives especially in light of the fact that this is being integrated into PHP 5.5 as the standard generic "opcache" solution? I think this is where the confusion comes from. It might be branded as ZO+ on Github, but that becomes irrelevant when it's part of core.

I've tried contacting Beberlei directly (the author of the change), on Twitter and via e-mail, but no response. Not getting any response is quite annoying as it's been a month since this change was made and whenever I update an existing site or publish a new site I have to deal with this.

I need to invest some time in finding out how I can maintain my own fork of OSS projects that pull changes in from the branched master but allow me to keep 1 or 2 files totally different. The other thing that drives me insane is the fact that the postgresql platform drivers can't implement GUID generators because it requires an extension be enabled on the server (seriously, solve with documentation, it's easy to detect programmatically as well) plus the choosing of a function, when there is obviously only one sane choice.

I am so grateful for the opportunity to develop with OSS, but the bureaucratic decision-by-committee stuff is so frustrating when you're an end-user and can't find anyone who gives half a crap about stuff that is just plain stupid but overlooked due to resources already spread thin or whatever may be the case. I would be happy to develop fixes as well, but when they languish because you can't find a maintainer that is familiar with the issue, interested in finding a fix, and has the time available to act as custodian of a pull request, it is incredibly demoralizing.

Comment by Benjamin Eberlei [ 20/Apr/13 ]

Fixed and released a Collections 1.1.1 version

Comment by Ross Cousens [ 23/Apr/13 ]

Thanks Benjamin, I am grateful for the fix! Happy coding!





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

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

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

Attachments: File DDC2383Test.php    

 Description   

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

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

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

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

My entites look like this:

//Entity/Foo.php

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

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

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

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

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

//Entity/Bar.php

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

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

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

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

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

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

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

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

//Entity/Baz.php

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

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

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

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

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

And fails on

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


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

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

Comment by Benjamin Eberlei [ 14/Apr/13 ]

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

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





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

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

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


 Description   

Hi,

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

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

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

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

Thanks



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

duplicate of DDC-2217

Comment by Doctrine Bot [ 16/May/14 ]

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





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

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

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

PHP 5.4.11



 Description   

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

The following code will produce error:

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

Test code:

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


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

Overwriting assocations in this way is not supported.

Comment by Arthur Bodera [ 01/May/13 ]

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





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

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

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


 Description   

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



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

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





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

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

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


 Description   

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

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

Message:

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



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

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





[DDC-2347] Refresh Uniqueidentifier ID from mssql of inserted Entity in doctrine2.3 Created: 13/Mar/13  Updated: 13/Mar/13

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

Type: Bug Priority: Minor
Reporter: Lucas Senn Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: dql
Environment:

Windows Server 2008 R2, Apache 2.2, Doctrine 2.3, PHP 5.4



 Description   

I don't want you to report something that isn't a bug.
But I read about problems with doctrine2 and mssql uniqueid's.
So First I asked a question at stackoverflow. No one could help me, and the only one who gave me a comment thought the same then me, that it looks like a bug.

If it isn't a bug I'm very sorry for this issue report.

Issue as reported in
http://stackoverflow.com/questions/15368082/refresh-uniqueidentifier-id-from-mssql-of-inserted-entity-in-doctrine2






[DDC-2345] convertObjectParameterToScalarValue() raises a notice Created: 12/Mar/13  Updated: 01/May/13  Resolved: 01/May/13

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

Type: Bug Priority: Minor
Reporter: Massimiliano Arione Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: None


 Description   

In Doctrine\ORM\AbstractQuery.php, the method convertObjectParameterToScalarValue() can raise a Notice.
This code:

$value = $values[$class->getSingleIdentifierFieldName()];

should be changed in this one:

if (isset($values[$class->getSingleIdentifierFieldName()])) {
    $value = $values[$class->getSingleIdentifierFieldName()];
}


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

Massimiliano Arione the current DQL implementation doesn't allow you to bind composite key identifiers as parameters, thus you will never reach that piece of code.

A test would be needed for this case.

Comment by Massimiliano Arione [ 12/Mar/13 ]

Unfortunately, I'm not really a Doctrine guru.
I can tell you that I'm getting that notice, using Sortable behavior with Symfony2.
This is a partial error stack:

1 in (...)/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php at line 282

2 at ErrorHandler ->handle ('8', 'Undefined index: id', '(...)/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php', '282', array('value' => object(MyEntity), 'class' => object(ClassMetadata), 'values' => array()))

3 in (...)/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php at line 282
at AbstractQuery ->convertObjectParameterToScalarValue (object(MyEntity))

4 in (...)/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php at line 260
at AbstractQuery ->processParameterValue (object(MyEntity))

5 in (...)/vendor/doctrine/orm/lib/Doctrine/ORM/Query.php at line 285
at Query ->processParameterMappings (array('group__1' => array('0')))

6 in (...)/vendor/doctrine/orm/lib/Doctrine/ORM/Query.php at line 258
at Query ->_doExecute ()

7 in (...)/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php at line 737
at AbstractQuery ->execute (null, '1')

8 in (...)/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php at line 538
at AbstractQuery ->getResult ()

9 in (...)/vendor/gedmo/doctrine-extensions/lib/Gedmo/Sortable/SortableListener.php at line 410
at SortableListener ->getMaxPosition (object(EntityManager), object(ClassMetadata), array('position' => 'rank', 'groups' => array('my_entity'), 'useObjectClass' => 'Meeting\GestioneBundle\Entity\MyRelatedEntity'), object(MyRelatedEntity))

10 in (...)/vendor/gedmo/doctrine-extensions/lib/Gedmo/Sortable/SortableListener.php at line 114
at SortableListener ->prePersist (object(LifecycleEventArgs))

11 in (...)/vendor/symfony/symfony/src/Symfony/Bridge/Doctrine/ContainerAwareEventManager.php at line 61
Comment by Marco Pivetta [ 12/Mar/13 ]

Massimiliano Arione having a composite primary key?

Comment by Massimiliano Arione [ 12/Mar/13 ]

Nope, just a plain "id".

Comment by Benjamin Eberlei [ 01/May/13 ]

Fixed in 2.4





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

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

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


 Description   

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

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

Message:

Fix for this error:

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



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

Marking as blocker - has to go in before 2.4

Comment by Benjamin Eberlei [ 03/Mar/13 ]

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

Comment by Marco Pivetta [ 03/Mar/13 ]

merged

Comment by Doctrine Bot [ 26/Jun/14 ]

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





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

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

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

debian 6, php 5.4.10



 Description   

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

The code used was:

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

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

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

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

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

The problem occurs, when doing a simple

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

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

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

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

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



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

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

Comment by Thomas Mayer [ 28/Feb/13 ]

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

However, this works fine.

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

Comment by Marco Pivetta [ 28/Feb/13 ]

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

Comment by Thomas Mayer [ 28/Feb/13 ]

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

Comment by Benjamin Eberlei [ 04/Mar/13 ]

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





[DDC-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-2314] getResults with numeric indexes for fields Created: 22/Feb/13  Updated: 26/Feb/13

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

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


 Description   

When executing a simple query with field names in SELECT clause, it is not possible to map field to numeric indexes.

This is an example that i would imagine to be useful:

SELECT c.id AS 0, c.name AS 1, l.text AS 2 FROM Category c LEFT JOIN c.label l

Thus, the resulting results could be numeric indexed array. It is useful for many situations: when working with an API which expects such arrays, or when using list to assign result fields to variables directly.

Query::HYDRATE_SCALAR does not achieve this, as one could think at first glance.






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

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

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

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

 Description   

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

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

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



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

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

Comment by Benjamin Eberlei [ 01/May/13 ]

Duplicate of DDC-2267





[DDC-2297] Add ConstraintException for parent row Created: 15/Feb/13  Updated: 15/Feb/13  Resolved: 15/Feb/13

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

Type: New Feature Priority: Trivial
Reporter: Daniel Lima Assignee: Benjamin Eberlei
Resolution: Won't Fix Votes: 0
Labels: None


 Description   

Currently there is no constraint check for entities that depends another one.
I always check the dependencies using repository. Something like this:

$childRepository = $em->getRepository('Child');
$parent = $em->getReference('app:Parent', $id);
$children = $childRepository->findBy(array('parent' => $parent));

if ($children) {
    throw new Exception('You can not delete this record. There are records related');
}
        
$em->remove($parent);
$em->flush();

This exception could be thrown in $em->flush(); or could look like:

 
try {
    $parentEntity = $em->gerReference('ParentEntity', $id);
    $em->remove($parentEntity);
    $em->flush();
catch (SomeORMNamespace\ConstraintException $e) {
    echo $e->getMessage(); //outs: You cannot remove this entity. There is another one related.
}

I think this functionality could be implemented through metadata on any sides of the relationship or on the @Entity mapping.

@Entity(children={'Child'}) //this is not a good attr name =)
class Parent {}

I know that is more app business logic related, but is it possible to implement this feature in next releases?



 Comments   
Comment by Benjamin Eberlei [ 15/Feb/13 ]

This is responsiblity of the the application developer.

You can implement this generically using parts of the API shown below:

$metadata = $entityManager->getClassMetadata("ClassName");

foreach ($metadata->associationMappings as $assoc) {
   if ($assoc['type'] & ClassMetadata::TO_ONE) {
      
   }
}




[DDC-2288] Schema Tool doesn't update collation on table level Created: 08/Feb/13  Updated: 08/Feb/13

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

Type: Improvement Priority: Minor
Reporter: Rickard Andersson Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: collation, schematool


 Description   

In Symfony2, when updating the collation option of a table, the schema tool doesn't recognize the change:

Changing from:

 
* @ORM\Table()

To:

 
* @ORM\Table(options={"collate"="utf8_swedish_ci"})

Results in:

 
$ php app/console doctrine:schema:update --dump-sql
Nothing to update - your database is already in sync with the current entity metadata.





[DDC-2287] Getter/Setter: generate "isEnabled()" instead of "getEnabled()" for boolean field in entity classes Created: 08/Feb/13  Updated: 10/Nov/14

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

Type: Improvement Priority: Minor
Reporter: Sukhrob Khakimov Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None

Issue Links:
Reference
relates to DDC-2924 doctrine:generate:entities docblocks ... Resolved

 Description   

It would be better if doctrine generated "isEnabled()" instead of "getEnabled()" for boolean field in entity classes. Because, it is more meaningful.



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

Not sure this kind of check should be handled. Starting to add all this kind of rules makes me think that it is becoming a big ball of mud

Comment by Joshua thijssen [ 31/Oct/14 ]

I agree that it would be hard to figure out which prefix to use (isEnabled() or hasEnabled() are both valid, depending on context).

However, it might be easy enough to check for a is<fieldname> or has<fieldname> method already present inside the entity, (https://github.com/doctrine/doctrine2/blob/f12c311a795b69a5f4853b079b3f8ad2c9867181/lib/Doctrine/ORM/Tools/EntityGenerator.php#L1360). If present, we could skip creating the getter as well.

This allows to (manually) change the getEnabled() into an isEnabled(), and future generations will not add the getEnabled() anymore.

It also makes it easier to confirm to PMD's booleanGetMethodName rule (http://phpmd.org/rules/naming.html#booleangetmethodname)

Comment by Marco Pivetta [ 10/Nov/14 ]

Getting back to this, I don't think we should alter codegen based on DBAL types, as per previous discussions in DDC-2924.

We're trying to decouple code generation from that, while this sort of approach increases coupling.

I'm inclined to reject the proposal until we split out the code generator into its own component.





[DDC-2286] Update documentation for collation Created: 08/Feb/13  Updated: 08/Feb/13

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

Type: Documentation Priority: Minor
Reporter: Rickard Andersson Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: collation, documentation


 Description   

The documentation at http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/faq.html#how-do-i-set-the-charset-and-collation-for-mysql-tables clearly states that the collation should be set at database level and then inherited for all tables created.

Digging through the code and reading this issue http://www.doctrine-project.org/jira/browse/DDC-2139 it's clear that this is no longer the case.






[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-2283] Paginator with orderBy in joined data retrieve bad result Created: 07/Feb/13  Updated: 26/Feb/13

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

Type: Improvement Priority: Minor
Reporter: Jean-Philippe THEVENOUX Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: paginator


 Description   

entity A have many entity B

If DQL is something like "select A, B from A join B order by A.field1, B.field2"
Then Paginator retrieve different Id by a query like :
"select distinct a.id, a.field1, b.field2 from ( ....) order by a.field1 ASC , b.field2 ASC limit 15 offset 0"

so, if a entity A have 20 entity B (and these sub-entity have all a different b.field2) then there's only 1 A retrieved






[DDC-2248] Expire result cache functionality not implemented Created: 19/Jan/13  Updated: 19/Jan/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.3, 2.3.1, 2.3.2
Fix Version/s: None

Type: Documentation Priority: Major
Reporter: Piotr Niziniecki Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

According to documentation expireResultCache, should force cache to update but it's not working... Why? Because functionality is not implemented. You can set _expireResultCache variable, but there is no place where this variable is being checked.



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

A cache profile can be set and cleaned. I suppose that `expireResultCache` is an old piece of code that survived the refactoring. Should just be removed and documented accordingly





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

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

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


 Description   

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



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

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

Do you have any example code for this?

Comment by Masaki Fujimoto [ 15/Jan/13 ]

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

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

// $ref => NULL


// MCode.php
<?php

namespace Enjoitech\BaseBundle\Entity;

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

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

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

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


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

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

Comment by Benjamin Eberlei [ 20/Jan/13 ]

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

Comment by Masaki Fujimoto [ 20/Jan/13 ]

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

Comment by Marco Pivetta [ 20/Jan/13 ]

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

Comment by Masaki Fujimoto [ 20/Jan/13 ]

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

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

Comment by Marco Pivetta [ 20/Jan/13 ]

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

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

Comment by Masaki Fujimoto [ 20/Jan/13 ]

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





[DDC-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-2238] doctrine:schema:update partially broken Created: 11/Jan/13  Updated: 01/May/13  Resolved: 01/May/13

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

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

OS X 10.7.5
PHP 5.4.4
Postgres SQL 9.1.6

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


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

 Description   

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

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

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

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

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

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



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

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

Comment by Tom Vogt [ 12/Jan/13 ]

requested dump of SchemaDiff

Comment by Tom Vogt [ 12/Jan/13 ]

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

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

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

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

Comment by Tom Vogt [ 15/Apr/13 ]

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

ALTER TABLE event ALTER priority SET ;

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

Comment by Benjamin Eberlei [ 01/May/13 ]

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

Comment by Benjamin Eberlei [ 01/May/13 ]

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





[DDC-2236] SUM(..) with Pagination gives incorrect result Created: 11/Jan/13  Updated: 10/Feb/13

Status: In Progress
Project: Doctrine 2 - ORM
Component/s: Tools
Affects Version/s: 2.2.3
Fix Version/s: None

Type: Documentation Priority: Minor
Reporter: Oleg Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: paginator
Environment:

Linux



 Description   

https://github.com/whiteoctober/Pagerfanta/issues/69

<?php
$query = $em->getRepository('M\E\Q')
->createQueryBuilder('q')
->select('q', 'SUM(q.price) AS amount')
->where('q.id IN(19, 20, 22)')
->groupBy('q.customer')
;

$pager = new Pagerfanta(new DoctrineORMAdapter($query));
$pager->setMaxPerPage(30);
$pager->setCurrentPage($request->query->get('page', 1));

$result = $pager->getCurrentPageResults();
print_r($result[0]['amount']); // 156.71 - Incorrect

$result = $query->getQuery()->getResult();
print_r($result[0]['amount']); // 553.47
?>

Sql for the above:

SELECT DISTINCT id0 FROM (SELECT q0_.id AS id0, SUM(q0_.price) AS sclr36 FROM Q q0_ WHERE q0_.id IN (19, 20, 22) GROUP BY q0_.customer_id) dctrn_result LIMIT 30 OFFSET 0
SELECT q0_.id AS id0, SUM(q0_.price) AS sclr36 FROM Q q0_ WHERE q0_.id IN (19, 20, 22) AND q0_.id IN ('19') GROUP BY q0_.customer_id
SELECT q0_.id AS id21, SUM(q0_.price) AS sclr36 FROM Q q0_ WHERE q0_.id IN (19, 20, 22) GROUP BY q0_.customer_id

Sql with fetchJoin = false (new DoctrineORMAdapter($query, false))

SELECT q0_.id AS id0, SUM(q0_.price) AS sclr36 FROM Quote q0_ WHERE q0_.id IN (19, 20, 22) GROUP BY q0_.customer_id LIMIT 30 OFFSET 0
SELECT q0_.id AS id0, SUM(q0_.price) AS sclr36 FROM Quote q0_ WHERE q0_.id IN (19, 20, 22) GROUP BY q0_.customer_id



 Comments   
Comment by Alexander [ 09/Feb/13 ]

Can you also test this with doctrine >= 2.3? The pagination code changed quite a lot.

Comment by Oleg [ 10/Feb/13 ]

Looks like no change

composer.json:
"doctrine/orm": "2.3.*",

php composer.phar update
Loading composer repositories with package information
Updating dependencies

  • Installing doctrine/common (2.3.0)
    Loading from cache
  • Installing doctrine/dbal (2.3.2)
    Loading from cache

then cleared cache but result is same
Here's the code

 
$query = $this->getDoctrine()->getEntityManager()->getRepository('MyBundle:Invoice')
  ->createQueryBuilder('q')
  ->select('q', 'SUM(q.amount) AS amount')
  ->groupBy('q.customer')
;
 
95 Connect	root@localhost on **
95 Query	SELECT DISTINCT id0 FROM (SELECT i0_.id AS id0, i0_.invoice_num AS invoice_num1, i0_.date AS date2, i0_.amount AS amount3, i0_.vat_amount AS vat_amount4, i0_.amount_paid AS amount_paid5, i0_.md5 AS md56, i0_.is_exported AS is_exported7, i0_.created AS created8, SUM(i0_.amount) AS sclr9 FROM Invoice i0_ GROUP BY i0_.customer_id) dctrn_result LIMIT 30 OFFSET 0
95 Query	SELECT i0_.id AS id0, i0_.invoice_num AS invoice_num1, i0_.date AS date2, i0_.amount AS amount3, i0_.vat_amount AS vat_amount4, i0_.amount_paid AS amount_paid5, i0_.md5 AS md56, i0_.is_exported AS is_exported7, i0_.created AS created8, SUM(i0_.amount) AS sclr9, i0_.customer_id AS customer_id10 FROM Invoice i0_ WHERE i0_.id IN ('2') GROUP BY i0_.customer_id
95 Query	SELECT i0_.id AS id0, i0_.invoice_num AS invoice_num1, i0_.date AS date2, i0_.amount AS amount3, i0_.vat_amount AS vat_amount4, i0_.amount_paid AS amount_paid5, i0_.md5 AS md56, i0_.is_exported AS is_exported7, i0_.created AS created8, SUM(i0_.amount) AS sclr9, i0_.customer_id AS customer_id10 FROM Invoice i0_ GROUP BY i0_.customer_id
130210 16:08:25	   95 Quit	

But I understand why that happens, it's due to group by and pagination nature.
The first query returns only one row with id "2", second query should be actually "..WHERE i0_.id IN ('2', '3', '4')"

If I do

$pager = new Pagerfanta(new DoctrineORMAdapter($query, false));

I get this sql

SELECT i0_.id AS id0, i0_.invoice_num AS invoice_num1, i0_.date AS date2, i0_.amount AS amount3, i0_.vat_amount AS vat_amount4, i0_.amount_paid AS amount_paid5, i0_.md5 AS md56, i0_.is_exported AS is_exported7, i0_.created AS created8, SUM(i0_.amount) AS sclr9, i0_.customer_id AS customer_id10 FROM Invoice i0_ LIMIT 30 OFFSET 0

I think it should be noted somewhere that if you do groupBy you should set fetchJoin to false?

Comment by Marco Pivetta [ 10/Feb/13 ]

Updating to Documentation issue.





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

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

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

Attachments: Text File SqlWalker.patch     File SqlWalkerTest.php    

 Description   

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

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



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

Hi Karma

Could you provide the failing DQL ?

Cheers

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

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

The SQL being generated is

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

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

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

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

Hi Drak,

Could you try to write a failing test case please ?

Cheers

Comment by Alexander [ 10/Feb/13 ]

ping!

Comment by Daniel Huss [ 14/Feb/13 ]

SqlWalker::walkInExpression() does this:

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

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

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

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

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

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

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

Comment by Daniel Huss [ 15/Feb/13 ]

failing test case

Comment by Daniel Huss [ 02/Apr/13 ]

Bug still present in release 2.3.3

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

Comment by Marco Pivetta [ 02/Apr/13 ]

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

Comment by Daniel Huss [ 02/Apr/13 ]

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

Comment by Benjamin Eberlei [ 08/Apr/13 ]

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

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

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





[DDC-2227] Add details about developer being responsible of inverse side of an association Created: 09/Jan/13  Updated: 09/Jan/13

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

Type: Documentation Priority: Minor
Reporter: Marco Pivetta Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: None


 Description   

As far as I know, docs don't explain that it is up to the developer to keep the object graph consistent instead of relying on Doctrine ORM for everything.

For example, for many to many, examples like following may be used:
https://gist.github.com/3121916






[DDC-2223] unable to use scalar function when a scalar expression is expected Created: 04/Jan/13  Updated: 04/Jan/13

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

Type: Bug Priority: Major
Reporter: Alexis Lameire Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: dql
Environment:

(not affected by this bug)



 Description   

the DQL Parser don't parse properly functions when a ScalarExpression is needed like of all case functions.

In fact first function token is interpreted as a T_IDENTIFIER and enter on line 1663 of Doctrine\ORM\Query\Parser class. in search of math operator, when not found this case considere that the token is a row element with no considération of the functions procession treated after.

fix of this bug consist to enclose the line 1672 by a if (!$this->_isFunction()).






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

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

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

Windows


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

 Description   

Getting a PHP Warning:

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

in ProxyFactory line 194.

I haven't more information in the warning.

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

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

This happens in dev environment, on a Windows machine.

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



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

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

We cannot fix this in Doctrine.

Comment by Matthieu Napoli [ 24/Dec/12 ]

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

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

Comment by Matthieu Napoli [ 27/Dec/12 ]

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

What can I do?

Thanks!

Comment by Matthieu Napoli [ 28/Feb/13 ]

Benjamin Eberlei ping: what can be done?

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

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

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

Comment by Marco Pivetta [ 28/Feb/13 ]

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

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

Comment by Matthieu Napoli [ 28/Feb/13 ]

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

Thanks for the feedback

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

Comment by Marco Pivetta [ 28/Feb/13 ]

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

Comment by Matthieu Napoli [ 28/Feb/13 ]

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

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

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

Comment by Marco Pivetta [ 28/Feb/13 ]

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

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

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

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

Comment by Matthieu Napoli [ 28/Feb/13 ]

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

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

Comment by Marco Pivetta [ 28/Feb/13 ]

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

Comment by Marco Pivetta [ 28/Feb/13 ]

Re-opening: the proxy factory could directly `eval()` the produced proxy code. The ProxyGenerator should no longer write the generat