[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-3369] Association Entity primary key composite with foreign keys Created: 04/Nov/14  Updated: 05/Nov/14  Resolved: 05/Nov/14

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

Type: Improvement Priority: Major
Reporter: Saydev Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: mapping, orm
Environment:

Projet Symfony 2



 Description   

Impossible to make an association between two entities in the following cases:

Entity1 with a composite primary key :
key1 (PK)
key2 (PK)

Entity2 with a composite primary key (with foreign key) :
key1 (PK FK)
key2 (PK FK)
key3 (PK)

How to connect two entities with this scenario?



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

This actually works as long as key1, key2 and key3 are user-generated values (such as UUIDs). We cannot support the case when these values are db-side generated.

Comment by Saydev [ 05/Nov/14 ]

Can we get around this problem ?





[DDC-3354] Replacing indexed item on association with indexBy cannot comply with unicity constraint Created: 17/Oct/14  Updated: 19/Oct/14

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

Type: Bug Priority: Major
Reporter: Charles Bouchard-Légaré Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: collection, mapping, orm


 Description   

Using a bidirectional one-to-many relation having an 'indexBy' clause on the owning side and a unique constraint over the indexed field and the 'mappedBy' field of the inverse side, replaced indexed fields being inserted before removed violated the unique constraint.

As stated in the code examples below, if done without the unique constraint, when replacing an indexed field, the row is replaced in the database (new one created, old one deleted).

Here is an example:

Yaml Mapping for Person and Email
Person:
    type: entity
    id:
        id:
            type: integer
            generator:
                strategy: AUTO
    oneToMany:
        emailAddresses:
            targetEntity: Email
            indexBy: name
            mappedBy: owner
            cascade: [ all ]
            orphanRemoval: true

Email:
    type: entity
    id:
        id:
            type: integer
            generator:
                strategy: AUTO
    fields:
        name:
            type: string
            nullable: false
        address:
            type: string
            nullable: false
    uniqueConstraints:
        unique_named_person_email:
            columns: [ owner_id, name ]
    manyToOne:
        owner:
            targetEntity: Person
            inversedBy:   emailAddresses
            joinColumn:
                name: owner_id
                referencedColumnName: id
PHP definitions for Person and Email
class Person {
    protected $id;
    /**
     * @var Collection|Email[] $emailAddresses
     */
    protected $emailAddresses;

    /**
     * I would expect this to work.
     */
    public function setEmailAddress_expected($name, $emailAddress)
    {
        /**
         * Expected to work but throws UniqueConstraintViolationException
         * If done without the 'unique_named_person_email' constraint', it 
         * works properly creating a new Email and deleting the old one.
         */
        $this->emailAddresses->set(
            (string) $name,
            new Email($this, (string) $name, (string) $emailAddress)
        );
    }
    
    /**
     * I would expect this to work.
     */
    public function setEmailAddress_expected_too($name, $emailAddress)
    {
        /**
         * Expected to work but throws UniqueConstraintViolationException
         * If done without the 'unique_named_person_email' constraint, it 
         * works properly creating a new Email and deleting the old one.
         */
        $this->emailAddresses->remove((string) $name);
        $this->emailAddresses->set(
            (string) $name,
            new Email($this, (string) $name, (string) $emailAddress)
        );
    }

    /**
     * Works
     */
    public function setEmailAddress_works($name, $emailAddress)
    {
        $existing = $this->emailAddresses->get((string) $name);
        if ($existing) {
            $existing->setAddress((string) $emailAddress);
        } else {
            $this->emailAddresses->set(
                (string) $name,
                new Email($this, (string) $name, (string) $emailAddress)
            );
        }
    }
}

class Email {
    protected $id;
    protected $owner;
    protected $name;
    protected $address;
    public function __construct($owner, $name, $address)
    {
        $this->owner = $owner;
        $this->name = $name;
        $this->address = $address;
    }

    /**
     * I am forced to create this method.
     */
    public function setAddress($address)
    {
        $this->address = $address;
    }
}

IMO, Using 'indexBy' on a one-to-many relation should automatically generate a unique constraint for the combination of the indexed field and the 'mappedBy' field.

Documentation states that

Fields that are used for the index by feature HAVE to be unique in the database. The behavior for multiple entities with the same index-by field value is undefined.

which is unclear (especially the use of the word 'database'). I wonder why indexes used for association should be unique for a whole table.



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

I wonder why indexes used for association should be unique for a whole table.

That's because we can't ensure that indexes aren't overwritten when hydrating a collection: that is what the behavior "undefined" stands for.

As for replacing values in the collection, that's how the ORM works in any case, as it inserts data before removing any data to avoid removes from causing FK constraint failures (see https://github.com/doctrine/doctrine2/blob/d361ed904e5d56711304b755b5b2a8484d9a35b6/lib/Doctrine/ORM/UnitOfWork.php#L347-L379)





[DDC-3349] Possibility to override order of fields of composite ID produced by Mapping Created: 13/Oct/14  Updated: 19/Oct/14

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

Type: New Feature Priority: Major
Reporter: tiger-seo Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: mapping

Issue Links:
Reference
relates to DDC-3352 [GH-1162] DDC-3349: Possibility to ov... Open

 Description   

So, the problem is when the one needs to use association key in composite identifier; they are added in the end of the identifier array, which is clearly not always suitable in regards to performance.
For example, following mapping:

Acme\DemoBundle\Entity\PageLocalFans:
    type: entity
    id:
        date:
            type: date
        page:
            associationKey: true
        countryCode:
            type: string
            length: 2
    fields:
        fans:
            type: integer
    manyToOne:
        page:
            targetEntity: Page
            joinColumn:
                name: page_id
                referencedColumnName: id
                onDelete: CASCADE

will turn into sql as:

CREATE TABLE page_local_fans (
  date         DATE       NOT NULL,
  country_code VARCHAR(2) NOT NULL,
  page_id      INT        NOT NULL,
  fans         INT        NOT NULL,
  INDEX IDX_7391EB36C4663E4 (page_id),
  PRIMARY KEY (date, country_code, page_id)
) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;

and there is no way to change the order of the primary from

PRIMARY KEY (date, country_code, page_id)

to

PRIMARY KEY (date, page_id, country_code)


 Comments   
Comment by tiger-seo [ 14/Oct/14 ]

i've done the PR for this, pls see https://github.com/doctrine/doctrine2/pull/1162

Comment by Doctrine Bot [ 17/Oct/14 ]

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





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

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

Type: Bug Priority: Critical
Reporter: Andrea Sprega Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: mapping, orm


 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?






[DDC-3339] [GH-1154] Hotfix/php 5.6 serialization fix Created: 06/Oct/14  Updated: 06/Oct/14  Resolved: 06/Oct/14

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4, 2.4.1, 2.4.2, 2.4.3, 2.4.4, 2.4.5
Fix Version/s: 2.4.6
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Marco Pivetta
Resolution: Fixed Votes: 0
Labels: mapping

Issue Links:
Reference
relates to DDC-3120 Warning: Erroneous data format for un... Resolved

 Description   

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

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

Message:

See DDC-3120 ( http://www.doctrine-project.org/jira/browse/DDC-3120 )

This PR provides a backport for the 2.4 branch



 Comments   
Comment by Steve Müller [ 06/Oct/14 ]

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

Comment by Dominik Zogg [ 06/Oct/14 ]

Thx you





[DDC-3325] No exception thrown when passing invalid option to mapXToY() in ClassMetadataInfo Created: 25/Sep/14  Updated: 19/Oct/14

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

Type: Bug Priority: Minor
Reporter: Thomas Konrad Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: mapping, orm
Environment:

Symfony2, Windows 7, PHP 5.4



 Description   

I recently ran into the problem that I wrongly specified the `joinColumn` option passed to the method `mapManyToOne` in the `ClassMetadataInfo` class:

    $metadata->mapManyToOne(array(
        // ...
        'joinColumn'   => array(
            'name' => 'column_id',
        )
    ));

This would be the intuitive way to define that mapping, as with Annotations it is also called `JoinColumn` (but yeah I know, there could possibly be multiple `JoinColumn` definitions). The right way to do it is:

    $metadata->mapManyToOne(array(
        // ...
        'joinColumns'   => array(array(
            'name' => 'column_id',
        ))
    ));

The actual bad experience that I had as a developer here is that no exception was through even though I had definitely passed a wrong configuration option to the mapping function. In fact, nothing happended, the `joinColumn` option was just ignored. It would be great in this case if an exception would be thrown so that it is clear to the developer that there is something wrong.

Thanks!






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

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: 0
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?






[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-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-3277] Yaml convert-mapping bug Created: 27/Aug/14  Updated: 01/Sep/14

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

Type: Bug Priority: Major
Reporter: Vladimir Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: mapping, orm, yaml, yml
Environment:

Windows+XAMPP, PHP5.3, Zend Framework 2



 Description   

I use yaml mapping in my project for better migration management. For example, I use

    orm:convert-mapping yml ./yml --from-database --namespace="User\Entity\\" --filter="User\Entity\User"

To make yml entites for my User module. In my yml I have smth like this:

      password:
            type: string
            nullable: false
            length: 256
            fixed: false
            comment: ''
        email:
            type: string
            nullable: false
            length: 64
            fixed: false
            comment: ''
        status:
            type: smallint
            nullable: false
            unsigned: false
            comment: ''

I can write a comment to column

         status:
                type: smallint
                nullable: true
                unsigned: false
                comment: '%some comment%'
                column: status

And when I perform migration comment disappears. Here https://github.com/doctrine/migrations/issues/184 I was adviced to use such construction:

    status:
        type: smallint
        nullable: true
        column: status
        options:
            unsigned: false
            comment: '%some comment%'

And It works! But convert-mapping generates wrong code. Does anyone know any way to generate a correct one with convert-mapping?



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

Seems like Christophe Coevoet started working on this: https://github.com/doctrine/doctrine2/pull/1123

Comment by Vladimir [ 29/Aug/14 ]

Thank you very much! Will with feature be available with update through composer?

Comment by Doctrine Bot [ 30/Aug/14 ]

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

Comment by Doctrine Bot [ 30/Aug/14 ]

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

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

Vladimir there is no release date scheduled for 2.5 yet. If you want to use the patch you will have to use "dev-master" version in your composer.json





[DDC-3228] ORM\Tools\Export\Driver\PhpExporter.php does not properly export manyToOne associations Created: 24/Jul/14  Updated: 24/Jul/14

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

Type: Bug Priority: Major
Reporter: Dan V Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: mapping, orm, schematool
Environment:

PHP 5.5.9-1ubuntu4 (cli)



 Description   

PhpExporter.php fails to check the association for manyToOne/oneToOne and exports all associations as oneToOne.

See https://github.com/doctrine/doctrine2/tree/master/lib/Doctrine/ORM/Tools/Export/Driver/PhpExporter.php#L116 where oneToOne is hardcoded if the bitmask matches either manyToOne or oneToOne.

As opposed to YamlExporter.php:

https://github.com/doctrine/doctrine2/tree/master/lib/Doctrine/ORM/Tools/Export/Driver/YamlExporter.php#L165

Which does roughly the same thing, but then properly sets the association type by checking the actual association on lines 186 through one 190:

https://github.com/doctrine/doctrine2/tree/master/lib/Doctrine/ORM/Tools/Export/Driver/YamlExporter.php#L186-L190






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

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

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

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



 Description   

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

{ ... }

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

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



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

Duplicates this issue





[DDC-3120] Warning: Erroneous data format for unserializing PHP5.6+ Created: 11/May/14  Updated: 06/Oct/14  Resolved: 27/Aug/14

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: Git Master
Fix Version/s: 2.5, 2.4.6
Security Level: All

Type: Bug Priority: Critical
Reporter: Cornelis Brouwers Assignee: Marco Pivetta
Resolution: Fixed Votes: 0
Labels: mapping, orm
Environment:

Webserver Apache/2.4.7 (Win32) OpenSSL/1.0.1e PHP/5.6.0beta2

and

PHP-CLI (Win32) PHP/5.6.0beta2


Issue Links:
Duplicate
is duplicated by DDC-3252 [GH-1109] DDC-3120 - PHP 5.6-RC3 comp... Resolved
Reference
is referenced by DDC-3156 [GH-1050] DDC-3120 -- Catch Reflectio... Resolved
is referenced by DDC-3339 [GH-1154] Hotfix/php 5.6 serializatio... Resolved

 Description   

Hi all,

There seems to be something strange going on in the method newInstance() of the class \Doctrine\ORM\Mapping\ClassMetadataInfo.

The original class method looks like this:

\Doctrine\ORM\Mapping\ClassMetadataInfo#newInstance()

    {
        if ($this->_prototype === null) {
            $this->_prototype = unserialize(sprintf('O:%d:"%s":0:{}', strlen($this->name), $this->name));
        }

        return clone $this->_prototype;
    }

What happens now when a class that implements \Serializable is that a "Warning: Erroneous data format for unserializing" shows up and the function unserialize() returns false.

That is because a class that implements \Serializable is expected to have the letter 'C' in the serialize string instead of the letter 'O'.

I've made a quick work-around like this:

\Doctrine\ORM\Mapping\ClassMetadataInfo#newInstance()

    {
        if ($this->_prototype === null) {
            $this->_prototype = @unserialize(sprintf('O:%d:"%s":0:{}', strlen($this->name), $this->name));
            if ($this->_prototype === false) {
                $this->_prototype = unserialize(sprintf('C:%d:"%s":0:{}', strlen($this->name), $this->name));
            }
        }

        return clone $this->_prototype;
    }

That seems to work in my isolated tests and with Symfony2 and Doctrine2 and FOSUserBundle together.

I've noticed this because the Model\User class from FOSUserBundle implements \Serializable.

I had to implement a check in Model\User class because when using 'C:%d:"%s":0:{}' the $serialized parameter of the unserialize method in the Model\User class is a empty string then.

That warning seems only to happen with PHP5.6+. PHP5.5.12 and below doesn't show that warning.

I hope someone can shine some light on this, thank you,

Cornelis.



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

Indeed, for PHP 5.4+ we should use

ReflectionClass#newInstanceWithoutConstructor()
Comment by Cornelis Brouwers [ 11/May/14 ]

Just tested it. That works as expected, far more better then the dirty hacks I did, thanks a lot!

Any idea when this would be implemented into the code?

Comment by Marco Pivetta [ 11/May/14 ]

Send a pull request and I'll merge it later today (we could also need a failing test with an entity implementing the Serializable interface)

Comment by Evert Harmeling [ 30/May/14 ]

Seems to be a problem in the latest PHP 5.4 version too.

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

Comment by Doctrine Bot [ 30/May/14 ]

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

Comment by Julian Reyes Escrigas [ 02/Jun/14 ]

I am facing this same error i have PHP 5.5.13, I'm using Symfony, Doctrine ORM and FOSUserBUndle

Comment by Marco Pivetta [ 02/Jun/14 ]

Julian Reyes Escrigas the patch landed in master (2.5.x) for now.

Comment by Marco Pivetta [ 02/Jun/14 ]

Merged via DDC-3147

Comment by Thomas Buhk [ 04/Jun/14 ]

When can we expect the version with this bugfix?

Comment by Anthony Rey [ 08/Jun/14 ]

Why don't you tag 2.4.3 version with this fix ? Because the error is already present in PHP 5.5.13 which is a stable version and it's a blocking issue when you're using FOSUserBundle for example. There is also no opened issue refering this version and the due date is in april.

Comment by Jovan Perovic [ 19/Jun/14 ]

I'm still seeing this bug, although my PHP_VERSION_ID is 50600

So, version based condition is no good...

Comment by Marco Pivetta [ 19/Jun/14 ]

The approach to be taken for 50600 is still under discussion in php-internals.

Comment by Cornelis Brouwers [ 20/Jun/14 ]

Hi all,

I've just downloaded PHP5.6RC1 and updated doctrine and the error is back indeed.

A little peek at the code starting on line 866 of file Doctrine\ORM\Mapping\ClassMetadataInfo.php shows this:

    public function newInstance()
    {
        if ($this->_prototype === null) {
            if (PHP_VERSION_ID === 50429 || PHP_VERSION_ID === 50513) {
                $this->_prototype = $this->reflClass->newInstanceWithoutConstructor();
            } else {
                $this->_prototype = unserialize(sprintf('O:%d:"%s":0:{}', strlen($this->name), $this->name));
            }
        }

        return clone $this->_prototype;
    }

As can be seen, PHP5.6 is out of the picture, it only checks for the exact versions 5.4.29 and 5.5.13.

So for the code to work correctly on PHP5.6 one can add PHP5.6 to the test condition, or just skip the test all together if you don't mind the old PHP5.3. According to PHP, ReflectionClass::newInstanceWithoutConstructor is available since PHP >= 5.4.0.

Greetings, Cornelis.

Comment by Marco Pivetta [ 21/Jun/14 ]

As I already pointed out, this is still being discussed in php internals. See http://news.php.net/php.internals/75009

This won't be dealt with in 5.6 until there's either a stable release or internals decides what has to be done.

Comment by Marco Pivetta [ 21/Jun/14 ]

Also, ReflectionClass#newInstanceWithoutConstructor() still doesn't cover the pre-existing "hack" using unserialize, so we're still waiting for a reliable API from PHP core.

Comment by Chase Noel [ 23/Jul/14 ]

Using PHP 5.6RC2 and ORM 2.4.4 I am still experiencing this issue. I have also tested with PHP 5.5.15 and I am still getting the issue. Do i need to be using a different build of ORM to have the fix applied?

Comment by pascall [ 23/Jul/14 ]

Hi,
I'm using 5.6.0beta3 and ORM 2.4.4 and i have the same probleme
Warning: Erroneous data format for unserializing .. in orm/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php line 872

and in current code in ClassMetadataInfo.php line 872 is :

public function newInstance()
{
if ($this->_prototype === null) {
if (PHP_VERSION_ID === 50429 || PHP_VERSION_ID === 50513)

{ $this->_prototype = $this->reflClass->newInstanceWithoutConstructor(); }

else {
$this->_prototype = unserialize(sprintf('O:%d:"%s":0:{}', strlen($this->name), $this->name));
}
}

return clone $this->_prototype;
}

Comment by Evert Harmeling [ 23/Jul/14 ]

As stated by Marco Pivetta; "This won't be dealt with in 5.6 until there's either a stable release or internals decides what has to be done.". And besides that 5.6 still is in development, not stable.
If you still want to use 5.6 you can fork the code and extend the 5.4 / 5.5 check to support 5.6.

Comment by Chase Noel [ 23/Jul/14 ]

5.6 has an RC which should mean a stable API, and that only bugs will be fixed before an official stable release?

Comment by Evert Harmeling [ 23/Jul/14 ]

Looking at http://news.php.net/php.internals/75966 it's still being discussed, and they are planning to have it fixed in RC3.

Comment by Marco Pivetta [ 23/Jul/14 ]

Internals still didn't get to a clear decision. Until then, we won't support 5.6 officially.

Comment by Ronan [ 24/Jul/14 ]

Same error encountered with PHP 5.5.13 (cli) (built: May 30 2014 10:43:29)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
with Zend OPcache v7.0.4-dev, Copyright (c) 1999-2014, by Zend Technologies
with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans

(PHP 5.5 installed via http://php-osx.liip.ch/)

Comment by Marco Pivetta [ 24/Jul/14 ]

Ronan what D2 version? We fixed it for 2.4.x (temporarily)

Comment by Ronan [ 24/Jul/14 ]

My bad: reading my composer.lock: doctrine/orm, v2.4.2, ref 0363a5548d9263f979f9ca149decb9cfc66419ab, "time": "2014-02-08 16:35:09"... Well.. this is was an old one !

`composer update` fixed it. Sorry for disturbing.

Comment by Chase Noel [ 12/Aug/14 ]

Im still getting this error running php 5.6RC2 and the dev-master(6ac19b04bfbd7a97aad5ed8c2abd6279ff5e0022) build of D2/orm. Am i missing something?

Comment by Marco Pivetta [ 12/Aug/14 ]

This was semi-fixed in PHP5.6-RC3, and it will be patched into ORM once doctrine/instantiator is out

Comment by Chase Noel [ 12/Aug/14 ]

Ok good to know. Thanks

Comment by Marco Pivetta [ 13/Aug/14 ]

Not yet fixed for PHP 5.6

Comment by Marco Pivetta [ 14/Aug/14 ]

Provided a hotfix proposal at https://github.com/doctrine/doctrine2/pull/1109 - please check it out with PHP 5.6.0-RC3 or later

Comment by Doctrine Bot [ 27/Aug/14 ]

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

Comment by Marco Pivetta [ 27/Aug/14 ]

Due to a new introduced dependency, this issue will only be solved for PHP 5.6 in 2.5.0 and later.

Comment by Doctrine Bot [ 28/Aug/14 ]

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

Comment by Dominik Zogg [ 10/Sep/14 ]

@ocramius would be great if there where backports for 2.4 and 2.3

Comment by Attila Bukor [ 28/Sep/14 ]

I agree with Dominik, we'd like to use the latest stable version and would need this patch.

Comment by Marco Pivetta [ 06/Oct/14 ]

This has been backported in DDC-3339





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

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

Type: New Feature Priority: Major
Reporter: Doctrine Bot Assignee: Marco Pivetta
Resolution: Fixed Votes: 0
Labels: mapping, postgresql, sqlite

Issue Links:
Dependency
depends on DBAL-900 [GH-600] Support for Partial Indexes ... Resolved
Reference
relates to DC-82 Conditional unique validator and index Closed

 Description   

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

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

Message:

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

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

Thanks for your time !



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

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

Comment by Doctrine Bot [ 16/May/14 ]

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

Comment by Doctrine Bot [ 02/Aug/14 ]

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

Comment by Doctrine Bot [ 19/Aug/14 ]

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

Comment by Doctrine Bot [ 05/Nov/14 ]

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

Comment by Doctrine Bot [ 05/Nov/14 ]

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





[DDC-3103] Is embedded class information in ClassMetadata is not stored when serializing. Created: 28/Apr/14  Updated: 29/Apr/14  Resolved: 29/Apr/14

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

Type: Bug Priority: Major
Reporter: Marco Jantke Assignee: Marco Pivetta
Resolution: Fixed Votes: 0
Labels: mapping, orm


 Description   

The isEmbeddedClass property on the ClassMetadata is not stored when the metadata is stored. This leads to errors when using cache drivers for metadata.



 Comments   
Comment by Marco Jantke [ 28/Apr/14 ]

I will create a PR for this issue.

Comment by Marco Jantke [ 29/Apr/14 ]

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

Comment by Marco Pivetta [ 29/Apr/14 ]

Merged: https://github.com/doctrine/doctrine2/commit/27845088e3ac46693abfddb8f76b501e2af58208





[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-3061] [GH-996] [DDC-3027] Embedded in MappedSuperclass Created: 31/Mar/14  Updated: 15/May/14  Resolved: 15/May/14

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

Type: Bug Priority: Minor
Reporter: Doctrine Bot Assignee: Guilherme Blanco
Resolution: Fixed Votes: 0
Labels: mappedsuperclass, mapping


 Description   

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

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

Message:

The fields from the MappedSuperclass embedded properties are getting mapped directly into the MappedSuperclass fields causing the error.

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



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

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

Comment by Doctrine Bot [ 15/May/14 ]

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





[DDC-2965] Error after changing IdGenerator to AssignedGenerator when for this entity class insert has been already executed Created: 08/Feb/14  Updated: 09/Feb/14  Resolved: 09/Feb/14

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

Type: Bug Priority: Major
Reporter: Piotr Śliwa Assignee: Marco Pivetta
Resolution: Invalid Votes: 0
Labels: mapping, persister

Issue Links:
Reference
is referenced by DDC-2966 [GH-942] DDC-2965 - Changing ID gener... Resolved

 Description   

When you persist and flush entity and then change id generator to AssignedGenerator (and id generator type to NONE) for this entity class and then you persist and flush new entity with assigned id, below error will occur:

Exception: [Doctrine\DBAL\Exception\DriverException] An exception occurred while executing 'INSERT INTO cms_emails (email) VALUES ' with params [13, "example@example.com"]:

SQLSTATE[HY000]: General error: 25 bind or column index out of range

There is test that reproduces this issue:

    public function testPersistEntityAndThenSwitchToAssignedIdGenerator()
    {
        $email = new \Doctrine\Tests\Models\CMS\CmsEmail();
        $email->email = 'example5@example.com';

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

        $this->assertNotNull($email->id);

        $classMetadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsEmail');
        $classMetadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE);
        $classMetadata->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());

        $id = 13;

        $newEmail = new \Doctrine\Tests\Models\CMS\CmsEmail();
        $newEmail->email = 'example@example.com';
        $newEmail->id = $id;

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

        $newEmail = $this->_em->find('Doctrine\Tests\Models\CMS\CmsEmail', $id);

        $this->assertNotNull($newEmail);
    }

The problem is in BasicEntityPersister because insertSql is cached and is not cleared after changing id generator. Binded parameters count doesn't match with insert query because there is new parameter: id.



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

Provided a possible fix at https://github.com/doctrine/doctrine2/pull/942

Comment by Doctrine Bot [ 09/Feb/14 ]

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

Comment by Benjamin Eberlei [ 09/Feb/14 ]

It is not a supported use case to change metadata after loading them.





[DDC-2901] entity-listeners are not propagated to children of mapped superclasses Created: 09/Jan/14  Updated: 19/Aug/14

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

Type: Bug Priority: Major
Reporter: Stuart Carnie Assignee: Fabio B. Silva
Resolution: Unresolved Votes: 0
Labels: mapping


 Description   

If I have event-listeners set on the subclass and mapped superclass, event-listeners will not be propagated, per this code. Conversely, lifecycle events are, per this



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

Stuart Carnie I lost the code references that you linked, since the code changed and the line numbers don't match anymore.

Any chance that you can provide a failing test for this issue, as well as update the links to reference a fixed commit hash or tag?

Comment by Stuart Carnie [ 19/Aug/14 ]

Marco Pivetta, I've updated the URIs in the description to the right tree

Comment by Marco Pivetta [ 19/Aug/14 ]

The code explicitly forbids inheriting listeners when the child class does not have any.

Fabio B. Silva can you provide any insight on why this decision was made?





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

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

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

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



 Description   

SYNOPSIS

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

ISSUE DETAILS

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

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

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

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

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

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

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

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

CODE

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

    PRIMARY KEY (id)
);

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

    PRIMARY KEY (id)
);

-- ...

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

    PRIMARY KEY (id)
);

-- ...

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

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

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

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

    use ConstructorArgs;

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

    // ...

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

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

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

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

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

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

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

    use ConstructorArgs;

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

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

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

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

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

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

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

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

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

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

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

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

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

    use ConstructorArgs;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    private $logger;

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

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

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

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

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

            return new View($gpa, 204);
        }

        return new View($form);
    }

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

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

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

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

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

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

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

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





[DDC-2817] EntityGenerator should add escape character ` for columns names. Created: 25/Nov/13  Updated: 25/Nov/13  Resolved: 25/Nov/13

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

Type: Bug Priority: Minor
Reporter: Shailesh Prakash Assignee: Marco Pivetta
Resolution: Won't Fix Votes: 0
Labels: mapping


 Description   

DBMS keywords like 'when' can clash with column names. A tool like this should add column name as escaped in annotation for entities.



 Comments   
Comment by Marco Pivetta [ 25/Nov/13 ]

doctrine doesn't fix bad naming decisions... That can be handled via a naming strategy instead.





[DDC-2791] Constant value in JoinColumn Created: 13/Nov/13  Updated: 13/Nov/13

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

Type: New Feature Priority: Major
Reporter: Pavel S. Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: joins, mapping, orm

Attachments: JPEG File realty_reference.jpeg    

 Description   

My situation:
I have realty entities (flat, house, ...) they have hundreds parameters, wich title places in REFERENCE table. For example House has a few floor materials (stone, wood, etc.) and I want to get them. But each parameter type defined by type_id field in REFERENCE table, for example for floor material is's 115. My raw SQL:
SELECT h.id,... FROM HOUSE h
LEFT JOIN object_detail mf /material_floor/ ON mf.realty_id = h.id AND mf.data_class = h.data_class AND mf.type_id = 115
LEFT JOIN Reference mfr ON mfr.city_id = h.city_id AND mfr.id = mf.detail_id

And its not possible to set type_id directly in join table






[DDC-2742] 2 ManyToMany relations to the same target entity make the schema update fail by default Created: 15/Oct/13  Updated: 15/Oct/13

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

Type: Bug Priority: Major
Reporter: Christophe Coevoet Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: mapping, schematool


 Description   

At some point in the Doctrine releases (I don't remember which version it was), the default naming of the join table of a ManyToMany relation changed from using the property name to using the name of the target entity.

This makes it impossible to use multiple ManyToMany relations to the same target entity in a class without naming join tables explicitly. A SchemaException is thrown by the SchemaTool when trying to update the schema.

Note that this issue is not caught by the SchemaValidator. It will display us that the mapping files are correct (before throwing the above exception in the second step when trying to compare it to the existing database)






[DDC-2671] YAML mapping: entity generation with inheritance does work Created: 11/Sep/13  Updated: 11/Sep/13

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

Type: Bug Priority: Major
Reporter: Peter Tulala Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: inheritance, mapping, yaml


 Description   

Entities inherited from parent entities should be defined as class Foo extends Bar. However YAML driver ignores inheritance hierarchy and does not use "extends" keyword at all.






[DDC-2669] YAML mapping: discriminator map exception Created: 10/Sep/13  Updated: 10/Sep/13

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

Type: Bug Priority: Minor
Reporter: Peter Tulala Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: mapping, yaml


 Description   

I'm getting this exception when I generate all entities from YAML using orm:generate-entities:

[Doctrine\ORM\Mapping\MappingException]
Entity class 'Entity\PersonIndividual' used in the discriminator map of class 'Entity\Person' does not exist.

My discriminator map defined in Entity.Person.dcm.yml:

discriminatorMap:
  1: PersonIndividual
  2: PersonCompany
  3: PersonSelfEmployed

Mapping driver probably generates entities in wrong order, so entities defined in discriminator map does not exist when entity Person is being generated.

Note: The easiest workaround is to temporarily remove discriminatorMap definition from entity, generate entities, then put discriminatorMap back and then generate entities again. It would be great if it would be possible to generate all entities in only one step.






[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-2199] Yaml driver does not take into account field @Version attribute Created: 14/Dec/12  Updated: 16/Dec/12  Resolved: 16/Dec/12

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

Type: Bug Priority: Blocker
Reporter: Georgy Galakhov Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 0
Labels: mapping, yaml


 Description   

Even if field has version: true attribute, Yaml driver does not set class metadata isVersioned and versionField properties. As a result optimistic lock cannot be used.



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

Fixed





[DDC-2189] Bidirectional one-to-many association with Class Table Inheritance do not work Created: 06/Dec/12  Updated: 24/Dec/12  Resolved: 24/Dec/12

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

Type: Bug Priority: Major
Reporter: Ro Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: Mapping
Environment:

PHP 5.4.8 (cli) (built: Oct 18 2012 13:02:07)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies

Fedora Linux 17

mysql Ver 14.14 Distrib 5.5.28, for Linux (x86_64) using readline 5.1


Attachments: File Box.php     File Box.php     File BoxItem.php     File BoxItem.php     File Item.php     File Item.php     File testing_box.sql    

 Description   

Bidirectional one-to-many association with Class Table Inheritance does not work. Example.

Entity Box;
Entity Item;
Entity BoxItem extends Item;

BoxItem has ManyToOne to Box;
Box has OneToMany to BoxItems;

Validation Error:
Got an error: Entities\Box: "The association Entities\Box#items refers to the owning side field Entities\BoxItem#box which does not exist.",



 Comments   
Comment by Marco Pivetta [ 06/Dec/12 ]

Not a blocker

Comment by Marco Pivetta [ 06/Dec/12 ]

Ro this looks invalid to me.

    /**
     * @MayToOne(targetEntity="Asmuo", inversedBy="items")
     * @JoinColumn(name="box_id", referencedColumnName="id")
     */
    protected $box;

What's `Asmuo`?

Comment by Ro [ 06/Dec/12 ]

Sorry, I did post wrong file BoxItem, my mistake, but the bug persists.

Comment by Marco Pivetta [ 06/Dec/12 ]

Just checked on my side with attached entities (changed some namespaces, see latest attached files) and everything's fine.
Ro you got a typo on one of your annotations, which is `MayToOne` and should be `ManyToOne`.

Comment by Benjamin Eberlei [ 24/Dec/12 ]

Error caused by Invalid mapping





[DCOM-257] [GH-342] Class metadata loading fallback hook Created: 11/Nov/14  Updated: 11/Nov/14

Status: Open
Project: Doctrine Common
Component/s: Class Loading
Affects Version/s: None
Fix Version/s: None

Type: New Feature Priority: Major
Reporter: Doctrine Bot Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: aliases, mapping, resolve-target-entities

Issue Links:
Dependency
is required for DDC-3385 [GH-1181] Support fetching entities b... Open

 Description   

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

Url: https://github.com/doctrine/common/pull/342

Message:

Enables loading class metadata when loading failed (in subclasses).

See doctrine/doctrine2#385

Note that I preferred inheritance to avoid having an `EventManager` in here, though it may be a perfectly acceptable dependency in this case, therefore it is up for discussion.






[DBAL-936] Doctrine type not found exception thrown before checking the comment Created: 10/Jul/14  Updated: 11/Jul/14

Status: Open
Project: Doctrine DBAL
Component/s: Schema Managers
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Maxime Veber Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: mapping, mysql


 Description   

Here is the piece of code:

$type = $this->_platform->getDoctrineTypeMapping($dbType);

// In cases where not connected to a database DESCRIBE $table does not return 'Comment'
if (isset($tableColumn['comment'])) {
    $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
    $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
}

The method `getDoctrineTypeMapping` throw an exception if the type is not found. But for example if you have an enum type (see the doctrine cookbook on the subject), the type is setted as comment.

Doctrine throw the exception before having the occasion to get the type via comment.

Here are two solutions:

  • Check for comment before throw the exception
  • Adding the enum type to the doctrine platform and mapping it to string





[DBAL-781] Doctrine maps tinyint with length > 1 to boolan Created: 10/Jan/14  Updated: 14/Jan/14  Resolved: 14/Jan/14

Status: Resolved
Project: Doctrine DBAL
Component/s: None
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Minor
Reporter: Stefano Kowalke Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: boolean, dbal, mapping, tinyint
Environment:

OSX 10.8, PHP 5.4, MySQL 5.6



 Description   

Why Doctrine maps any tinyint, regardless its length to boolean type. According to the MySQL Documentation only tinyint(1) is equivalent to boolean. I searched the web and found only out that this is the way how Doctrine it does but not why, so I have to assume its a bug.

Hope someone who knows Doctrine better could enlighten me



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

Stefano Kowalke The length parameter for MySQL's integer does not have any effect unless you use it in conjunction with the ZEROFILL attribute. It does not have any meaning concerning min or max value and the storage requirements for that specific type but only specifies the display length for zerofill characters.

M indicates the maximum display width for integer types. For floating-point and fixed-point types, M is the total number of digits that can be stored. For string types, M is the maximum length. The maximum allowable value of M depends on the data type.

As MySQL does not have a native boolean type, Doctrine uses it to map it's own boolean type as it is the one that comes closest to a "boolean" type column. This is not a bug in Doctrine but an expected behaviour.
Hope I could clarify this.

Comment by Stefano Kowalke [ 11/Jan/14 ]

Hey Steve, thanks for your detailed informations. This helped me to understand the behavior and gave me a direction how to get more background informations.





[DBAL-662] Supporting PHP 5.5 DateTimeImmutable Created: 14/Nov/13  Updated: 02/Jul/14

Status: Open
Project: Doctrine DBAL
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: New Feature Priority: Minor
Reporter: Christophe Coevoet Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 3
Labels: mapping, schematool


 Description   

Introducing new types converting dates into a DateTimeImmutable rather than a DateTime could be useful for applications prefering the use of immutable datetimes (and relying on PHP 5.5+).

The existing types already support setting a DateTimeImmutable in a field mapped with the datetime type, as it does not check the value against DateTime but only expects a format method. but the conversion from DB to PHP will always produce a mutable DateTime instance, thus preventing to use the immutable flavour consistently.

Not that this is a low priority issue as any code interacting with third party packages will probably need to use DateTime anyway because of the typehints (typehinting DateTimeInterface would not work if you need to keep compatibility with 5.4)

If DBAL 3.0 bumps the minimal supported version to 5.5 (which might be possible depending of the release date of 3.0), we could decide to break BC and use the immutable flavour in the datetime type directly.



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

Christophe Coevoet Should we mark that for 3.0 as suggested? Or do you see any need/possibility of implementing this already in 2.x branch?

Comment by Yaroslav Nechaev [ 02/Jul/14 ]

Please add this feature. Mutable DateTime causes too much trouble: now we have to use clone in every getter and setter just in case someone modifies the value afterwards and spoils the value stored in entity.

Comment by Steve Müller [ 02/Jul/14 ]

Yaroslav Nechaev I don't think we can support this before Doctrine 3.0 without breaking BC as Christophe Coevoet already stated because it would require us to bump the minimal supported PHP version to 5.5 (which currently is 5.3.2).





[DBAL-529] databasenames including dashes not correctly supported Created: 24/May/13  Updated: 26/May/13  Resolved: 26/May/13

Status: Resolved
Project: Doctrine DBAL
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Andy Rosslau Assignee: Benjamin Eberlei
Resolution: Invalid Votes: 0
Labels: annotationdriver, mapping, yml


 Description   

I'm having a legacy Database including a dash in its name:

"my-db"

which includes tables I want to work with.

The EntityMapping would be the following:

yml

My\TestBundle\Entity\Stuff:
    type: entity
    table: my-db.stuff
    fields:
        id:
...

annotation

/**
 * @ORM\Entity()
 * @ORM\Table(name="my-db.stuff")
 */

Both concludes in a Query (SELECT, INSERT etc.) which won't work:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-db.stuff t0 WHERE[...]

I found a simple fix by trial and Error. Just put a "`" in front of the databasename:

yml

My\TestBundle\Entity\Stuff:
    type: entity
    table: `my-db.stuff
    fields:
        id:
...

annotation

/**
 * @ORM\Entity()
 * @ORM\Table(name="`my-db.stuff")
 */

Although this fix works, it feels wrong.
Moreover, to prevent confusing other developers, this should be fixed to one the following styles.

annotation

/**
 * @ORM\Entity()
 * @ORM\Table(name="`my-db`.stuff")
 */

OR

annotation

/**
 * @ORM\Entity()
 * @ORM\Table(name="my-db.stuff")
 */


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

This is the correct behavior, autoquoting is more painful than helpful, so we don't do it.

The explicit escaping with ` is documented to be the proper fix for quoting.

Comment by Andy Rosslau [ 26/May/13 ]

So? I thougt there is any autoquoting, as I recognized a query would look like that, when I put the database name in ` (eg. `my-db`.table).

sample-query (not working)

INSERT INTO `my-db``.table ...

Thats why I reported this issue. Only a single ` would work.. Query would look like this (correct)

INSERT INTO `my-db`.table ...

So as you can see the second ` is added automatically.





Generated at Fri Nov 21 20:43:41 UTC 2014 using JIRA 6.2.3#6260-sha1:63ef1d6dac3f4f4d7db4c1effd405ba38ccdc558.