[DDC-3234] Empty properties when filtering collections Created: 30/Jul/14  Updated: 31/Jul/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.5, 2.4.2
Fix Version/s: 2.x
Security Level: All

Type: Bug Priority: Major
Reporter: Diogo Domanski de Souza Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: Collection, Criteria, orm
Environment:

PHP 5.5.9, Nginx 1.4.6, PHP FPM, Zend Framework 2.3.1, Linux Ubuntu 14.04



 Description   

I'm facing some troubles when filtering an entity association (ArrayCollection) by using Criteria.

The scenario is the following: I have 3 entities:

User.php
<?php

namespace Entity;

use Doctrine\ORM\Mapping as ORM;
use \Doctrine\Common\Collections\Criteria;
use Zend\Stdlib\Hydrator;

/**
 * User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity(repositoryClass="Entity\UserRepository")
 * @ORM\HasLifecycleCallbacks
 * @author domanski
 */
class User implements \Serializable {
	/**
	 *
	 * @ORM\Id
	 * @ORM\Column(name="id", type="integer", nullable=false)
	 * @ORM\GeneratedValue(strategy="AUTO")
	 * @var integer
	 */
	private $id;

	/**
	 * @ORM\Column(name="delete_date", type="datetime")
	 * @var \DateTime
	 */
	private $deleteDate;
	
	public function __construct(array $options = array()) {
		if (!empty($options))
			$this->hydrate($options);
	}

	public function hydrate(array $options = array(), \Doctrine\ORM\EntityManager $em = null) {
		$hydrator = new Hydrator\ClassMethods();
		$hydrator->hydrate($options, $this);
	}

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

	/**
	 * 
	 * @param int $id
	 * @return \Entity\User
	 */
	public function setId($id) {
		$this->id = $id;
		return $this;
	}

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

	/**
	 * @param \DateTime|null $deleteDate
	 * @return \Entity\User
	 */
	public function setDeleteDate($deleteDate = null) {
		$this->deleteDate = $deleteDate;
		return $this;
	}

	/**
	 * 
	 * @return array
	 */
	public function toArray() {
		$result = array(
			'id' => $this->getId(),
			'delete_date' => $this->getDeleteDate()
		);

		return $result;
	}

}
FieldWorker.php
<?php

namespace Entity;

use Doctrine\ORM\Mapping as ORM;
use \Doctrine\Common\Collections\Criteria;

use Zend\Stdlib\Hydrator;

/**
 * Description of FieldWorker
 *
 * @ORM\Entity(repositoryClass="Entity\FieldWorkerRepository")
 * @ORM\Table(name="field_worker")
 * @ORM\HasLifecycleCallbacks
 * @author domanski
 */
class FieldWorker {
	
	/**
	 * This attribute must exist so the inverse join with any other entity can work
	 * 
	 * @ORM\Id
	 * @ORM\Column(type="integer", name="user_id")
	 * @var string
	 */
	protected $id;
	
	/**
	 * 
	 * @ORM\OneToOne(targetEntity="Entity\User")
	 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
	 * @var \Entity\User
	 */
	protected $user;
	
	public function __construct($options = array()) {		
		if(!empty($options))
			$this->hydrate($options);
	}
	
	public function hydrate(array $options = array(), \Doctrine\ORM\EntityManager $em = null) {
		if(!empty($em)) {
			// user
			if(isset($options['user']))
				$options['user'] = $em->getReference('Entity\User', $options['user']);
			else if(isset($options['user_id']))
				$options['user'] = $em->getReference('Entity\User', $options['user_id']);
						
		}
		
		$hydrator = new Hydrator\ClassMethods();
		$hydrator->hydrate($options, $this);
	}

	/**
	 * 
	 * @return \Entity\User
	 */
	public function getUser() {
		return $this->user;
	}

	/**
	 * 
	 * @param \Entity\User $user
	 * @return \Entity\FieldWorker
	 */
	public function setUser(\Entity\User $user) {
		$this->user = $user;
		$this->id = $user->getId();
		return $this;
	}
	
	/**
	 * 
	 * @return array
	 */
	public function toArray() {
		return $this->getUser()->toArray();
	}
}
Stage.php
<?php

namespace Obra\Entity;

use Doctrine\ORM\Mapping as ORM;
use Zend\Stdlib\Hydrator;
use Doctrine\Common\Collections\Criteria;

/**
 * Description of Stage
 *
 * @ORM\Table(name="stage")
 * @ORM\Entity(repositoryClass="Entity\StageRepository")
 * @ORM\HasLifecycleCallbacks
 * @author domanski
 */
class Stage {

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

	/**
	 * @ORM\ManyToMany(targetEntity="Entity\FieldWorker")
	 * @ORM\JoinTable(name="stage_field_worker",
	 * 		joinColumns={@ORM\JoinColumn(name="stage_id", referencedColumnName="id")},
	 * 		inverseJoinColumns={@ORM\JoinColumn(name="field_worker_id", referencedColumnName="user_id")}
	 * 	)
	 * @var \Doctrine\Common\Collections\ArrayCollection
	 */
	private $fieldWorkers;

	public function __construct(array $options = array()) {
		$this->fieldWorkers = new \Doctrine\Common\Collections\ArrayCollection();

		if (!empty($options))
			$this->hydrate($options);
	}

	public function hydrate(array $options = array(), \Doctrine\ORM\EntityManager $em = null) {
		$hydrator = new Hydrator\ClassMethods();
		$hydrator->hydrate($options, $this);
	}

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

	/**
	 * 
	 * @param int $id
	 * @return \Entity\Stage
	 */
	public function setId($id) {
		$this->id = $id;
		return $this;
	}

	/**
	 * 
	 * @return \Doctrine\Common\Collections\ArrayCollection
	 */
	public function getFieldWorkers() {
		$criteria = Criteria::create()
				->where(Criteria::expr()->isNull("user.deleteDate"))
				->orderBy(array("user.name" => Criteria::ASC));

		return $this->fieldWorkers->matching($criteria);
	}

	/**
	 * 
	 * @return \Entity\Stage
	 */
	public function clearFieldWorkers() {
		$this->fieldWorkers->clear();
		return $this;
	}

	/**
	 * 
	 * @param \Entity\FieldWorker $fieldWorker
	 * @return \Entity\Stage
	 */
	public function addFiscal(\Entity\FieldWorker $fieldWorker) {
		$this->fieldWorkers->add($fieldWorker);
		return $this;
	}

	/**
	 * 
	 * @return array
	 */
	public function toArray() {
		$result = array(
			"id" => $this->getId(),
			"field_workers" => array()
		);

		foreach ($this->getFieldWorkers() as $fieldWorker) {
			$result['field_workers'][] = $fieldWorker->toArray();
		}

		return $result;
	}
}

The problem is that whenever the Stage::getFieldWorkers() method is invoked, the list of associated field workers is returned correctly, however if I try to retrieve the respective user of any field worker, it is NULL.

For example:

$stageEntity = $em->getRerefence('Entity\Stage', 1);
$fieldWorkers = $stageEntity->getFieldWorkers();

foreach($fieldWorkers as $fieldWorker) {
   $userId = $fieldWorker->getUser()->getId(); // This throws an error message saying that the result of getUser() is NULL
}

Another example would be if I try to call $stageEntity->toArray() (because it does the same thing as show above).

The database tables are as following:

Database tables creation
CREATE TABLE `user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `delete_date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `field_worker` (
  `user_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`user_id`),
  CONSTRAINT `fk_field_worker_user1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE `stage` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE `stage_field_worker` (
  `stage_id` int(10) unsigned NOT NULL,
  `field_worker_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`stage_id`,`field_worker_id`),
  KEY `fk_stage_field_worker_stage_idx` (`stage_id`),
  KEY `fk_stage_field_worker_field_worker_idx` (`field_worker_id`),
  CONSTRAINT `fk_stage_field_worker_field_worker` FOREIGN KEY (`field_worker_id`) REFERENCES `field_worker` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fk_stage_field_worker_stage` FOREIGN KEY (`stage_id`) REFERENCES `stage` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `user` SET `id` = 1;
INSERT INTO `field_worker` SET `user_id` = 1;
INSERT INTO `stage` SET `id` = 1;
INSERT INTO `stage_field_worker` SET `stage_id` = 1, `field_worker_id` = 1;

After hours trying to understand what was wrong, I decided to make a test and modify the Stage::getFieldWorkers() method by removing the filtering Criteria:

public function getFieldWorkers() {
    return $this->fieldWorkers;
}

By simply doing that, the getUser() method started to return an entity of type User (as expected).

I am not a Doctrine ORM expert, but there seems to be something wrong with ArrayCollection filtering (matching() method)



 Comments   
Comment by Diogo Domanski de Souza [ 30/Jul/14 ]

The same problem occurs with QueryBuilder. For example:

StageRepository.php
<?php

namespace Entity;

use Doctrine\ORM\EntityRepository;

/**
 * Description of StageRepository
 *
 * @author domanski
 */
class StageRepository extends EntityRepository 
{

	public function findByFieldWorkerId($fieldWorkerId) {
		$qb = $this->getEntityManager()->createQueryBuilder()
			->select('s')
			->from('Entity\Stage', 's')
			->innerJoin('s.fieldWorkers', 'f')
			->innerJoin('f.user', 'u', \Doctrine\ORM\Query\Expr\Join::WITH, "u.deleteDate IS NULL AND u.id = :field_worker_id")
				->setParameter('field_worker_id', $fieldWorkerId);

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

If I try to iterate over the result of StageRepository::findByFieldWorkerId() and call toArray() of any element, I get the same error. I've even tried to remove the inner join with User entity from query:

	public function findByFieldWorkerId($fieldWorkerId) {
		$qb = $this->getEntityManager()->createQueryBuilder()
			->select('s')
			->from('Entity\Stage', 's')
			->innerJoin('s.fieldWorkers', 'f');

		return $qb->getQuery()->getResult();
	 }
Comment by Marco Pivetta [ 30/Jul/14 ]

I suspect that something is wrong in your mappings then...

Comment by Diogo Domanski de Souza [ 31/Jul/14 ]

Hi Marco,

The mappings are shown above. The only thing I did was to omit some entities/tables properties/columns that don't have to see with the associations - except the field worker (table and Entity) and stage_field_worker table, that are fully presented.

Maybe is important to notice that the field_worker table has only one column (user_id) that is primary key and foreign key (referencing user.id).

Thanks for you support





[DDC-3233] [GH-1092] Arbitrary Join count walkers solution Created: 30/Jul/14  Updated: 30/Jul/14

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

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


 Description   

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

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

Message:

Possible solution for Arbitrary Join problem in pagination count
walkers:
https://groups.google.com/forum/#!topic/doctrine-user/rpPYCDNKOU8

Added a condition to test query component against SelectStatement from
clause






[DDC-3231] [GH-1089] Entity repository generator default repository Created: 27/Jul/14  Updated: 27/Jul/14

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

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


 Description   

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

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

Message:






[DDC-3230] Bug in clear cache Created: 25/Jul/14  Updated: 25/Jul/14

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

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

Windows 7 64bits
PHP 5.5.4 32 bits
pdo_sql_srv 3.0.2 for php 5.5 32 bits
symfony 2.5
gedmo deletable @ dev-master
Redis 2.8.12
PHPRedis php_redis-2.2.5-5.5-nts-vc11-x86
IIS 7.5



 Description   

1. Redis is used for cache/meta/result caching.
2. Entity has property $deleted with gedmo deletable on it.
3. Removing property $deleted (and all related annotations)
4. Symfony commands:

php app/console doctrine:cache:clear-metadata
php app/console doctrine:cache:clear-query
php app/console doctrine:cache:clear-result
php app/console cache:clear --env=prod --no-debug <-- error on this command

5. [ReflectionException]
Property Entity::$deleted does not exist

Trace:

#0 \vendor\doctrine\orm\lib\Doctrine\ORM\Mapping\ClassMetadataInfo.php(989)
#1 \vendor\doctrine\orm\lib\Doctrine\ORM\Mapping\ClassMetadataFactory.php(571)
#2 \vendor\doctrine\common\lib\Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory.php(210) <-- CacheRedis driver called here
#3 \vendor\doctrine\common\lib\Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory.php(114)
#4 \vendor\symfony\symfony\src\Symfony\Bridge\Doctrine\CacheWarmer\ProxyCacheWarmer.php(69)
#5 \vendor\symfony\symfony\src\Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerAggregate.php(48)
#6 \app\bootstrap.php.cache(2513)
#7 \app\bootstrap.php.cache(2284)
#8 \vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Command\CacheClearCommand.php(128)
#9 \vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Command\CacheClearCommand.php(90)
#10 \vendor\symfony\symfony\src\Symfony\Component\Console\Command\Command.php(252)
#11 \vendor\symfony\symfony\src\Symfony\Component\Console\Application.php(894)
#12 \vendor\symfony\symfony\src\Symfony\Component\Console\Application.php(193)
#13 \vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Console\Application.php(96)
#14 \vendor\symfony\symfony\src\Symfony\Component\Console\Application.php(124)
#15 \app\console(27)

Why do i think this is a Doctrine bug and not a Symfony bug? Because

php app/console doctrine:cache:clear-metadata
php app/console doctrine:cache:clear-query
php app/console doctrine:cache:clear-result

have been called successfully so RedisCache should not return cache with $this->fieldMappings containing key "deleted"






[DDC-3229] Error when running the tests Created: 24/Jul/14  Updated: 24/Jul/14

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

Type: Bug Priority: Major
Reporter: Jeroen De Dauw Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Fresh clone at 089cca636e0e44a70dd9167b7d813762ea80daca.

php -v
PHP 5.5.9-1ubuntu4.3 (cli) (built: Jul 7 2014 16:36:58)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
with Zend OPcache v7.0.3, Copyright (c) 1999-2014, by Zend Technologies
with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans

j@wd42:~/workspace/doctrine2$ phpunit
PHPUnit 4.3-ge243de0 by Sebastian Bergmann.

Configuration read from /home/j/workspace/doctrine2/phpunit.xml.dist

............................................................. 61 / 2500 ( 2%)
........S.................................................... 122 / 2500 ( 4%)
............................................................. 183 / 2500 ( 7%)
............................................................. 244 / 2500 ( 9%)
............................................................. 305 / 2500 ( 12%)
............................................................. 366 / 2500 ( 14%)
.........................S...SSSS.S.......................... 427 / 2500 ( 17%)
............................................................. 488 / 2500 ( 19%)
....................................................SS....... 549 / 2500 ( 21%)
............................................................. 610 / 2500 ( 24%)
............................................................. 671 / 2500 ( 26%)
............................................................. 732 / 2500 ( 29%)
............................................................. 793 / 2500 ( 31%)
........................................................S.SSS 854 / 2500 ( 34%)
SSSSSSSSS.................................................... 915 / 2500 ( 36%)
..........................................SS................. 976 / 2500 ( 39%)
.............S...S...........S..............................S 1037 / 2500 ( 41%)
........PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 65552 bytes) in /home/j/workspace/doctrine2/vendor/doctrine/common/lib/Doctrine/Common/Proxy/ProxyGenerator.php on line 280
PHP Stack trace:
PHP 1.

{main}

() /usr/bin/phpunit.phar:0
PHP 2. PHPUnit_TextUI_Command::main() /usr/bin/phpunit.phar:586
PHP 3. PHPUnit_TextUI_Command->run() phar:///usr/bin/phpunit.phar/phpunit/TextUI/Command.php:132
PHP 4. PHPUnit_TextUI_TestRunner->doRun() phar:///usr/bin/phpunit.phar/phpunit/TextUI/Command.php:179
PHP 5. PHPUnit_Framework_TestSuite->run() /home/j/workspace/doctrine2/vendor/phpunit/phpunit/src/TextUI/TestRunner.php:423
PHP 6. PHPUnit_Framework_TestSuite->run() /home/j/workspace/doctrine2/vendor/phpunit/phpunit/src/Framework/TestSuite.php:715
PHP 7. PHPUnit_Framework_TestCase->run() /home/j/workspace/doctrine2/vendor/phpunit/phpunit/src/Framework/TestSuite.php:715
PHP 8. PHPUnit_Framework_TestResult->run() /home/j/workspace/doctrine2/vendor/phpunit/phpunit/src/Framework/TestCase.php:672
PHP 9. PHPUnit_Framework_TestCase->runBare() /home/j/workspace/doctrine2/vendor/phpunit/phpunit/src/Framework/TestResult.php:654
PHP 10. PHPUnit_Framework_TestCase->runTest() /home/j/workspace/doctrine2/vendor/phpunit/phpunit/src/Framework/TestCase.php:734
PHP 11. ReflectionMethod->invokeArgs() /home/j/workspace/doctrine2/vendor/phpunit/phpunit/src/Framework/TestCase.php:859
PHP 12. Doctrine\Tests\ORM\Functional\Ticket\DDC1436Test->testIdentityMap() /home/j/workspace/doctrine2/vendor/phpunit/phpunit/src/Framework/TestCase.php:859
PHP 13. Doctrine\ORM\AbstractQuery->getOneOrNullResult() /home/j/workspace/doctrine2/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1436Test.php:42
PHP 14. Doctrine\ORM\AbstractQuery->execute() /home/j/workspace/doctrine2/lib/Doctrine/ORM/AbstractQuery.php:766
PHP 15. Doctrine\ORM\AbstractQuery->executeIgnoreQueryCache() /home/j/workspace/doctrine2/lib/Doctrine/ORM/AbstractQuery.php:923
PHP 16. Doctrine\ORM\Internal\Hydration\AbstractHydrator->hydrateAll() /home/j/workspace/doctrine2/lib/Doctrine/ORM/AbstractQuery.php:977
PHP 17. Doctrine\ORM\Internal\Hydration\ObjectHydrator->hydrateAllData() /home/j/workspace/doctrine2/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php:147
PHP 18. Doctrine\ORM\Internal\Hydration\ObjectHydrator->hydrateRowData() /home/j/workspace/doctrine2/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php:160
PHP 19. Doctrine\ORM\Internal\Hydration\ObjectHydrator->getEntity() /home/j/workspace/doctrine2/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php:432
PHP 20. Doctrine\ORM\UnitOfWork->createEntity() /home/j/workspace/doctrine2/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php:268
PHP 21. Doctrine\Common\Proxy\AbstractProxyFactory->getProxy() /home/j/workspace/doctrine2/lib/Doctrine/ORM/UnitOfWork.php:2714
PHP 22. Doctrine\Common\Proxy\AbstractProxyFactory->getProxyDefinition() /home/j/workspace/doctrine2/vendor/doctrine/common/lib/Doctrine/Common/Proxy/AbstractProxyFactory.php:119
PHP 23. Doctrine\Common\Proxy\ProxyGenerator->generateProxyClass() /home/j/workspace/doctrine2/vendor/doctrine/common/lib/Doctrine/Common/Proxy/AbstractProxyFactory.php:218
PHP 24. strtr() /home/j/workspace/doctrine2/vendor/doctrine/common/lib/Doctrine/Common/Proxy/ProxyGenerator.php:280






[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-3226] Unable to escape field names in YAML notation Created: 24/Jul/14  Updated: 24/Jul/14

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

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

PHP Version 5.5.11
MySQL 5.6.16
Darwin Kernel Version 13.3.0
Mac OS 10.9.3



 Description   

As in DDC-1759, I wanted to use some reserved words as my field names (same case: MySQL-backed key-value storage).
DDC-1759 was resolved by escaping the column names in field annotations. However, I'm using YAML files to store my mappings, and I couldn't find a way to set up an escaped field name there.






[DDC-3224] getResult(HYDRATE_OBJECT) with joined query is returning reduced number of rows Created: 23/Jul/14  Updated: 23/Jul/14

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

Type: Bug Priority: Critical
Reporter: gondo Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: orm
Environment:

osx, PHP-FPM 5.5.13, nginx/1.6.0, mysql 5.6.19 Homebrew



 Description   

given that i have these 2 entities (pseodocode):

/**
 * @ORM\Table(name="entity1", options={"collate"="utf8_unicode_ci", "charset"="utf8"})
 * @ORM\Entity(repositoryClass="Entity1Repository")
 */
class Entity1 {
    /**
     * @var integer
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

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

    /**
     * @var Entity2[]
     * @ORM\OneToMany(targetEntity="Entity2", mappedBy="entity1")
     */
    protected $entity2;
}

/**
 * @ORM\Table(name="entity2", options={"collate"="utf8_unicode_ci", "charset"="utf8"})
 * @ORM\Entity()
 */
class Entity2 {
    /**
     * @var integer
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var \DateTime
     * @ORM\Column(name="date", type="datetime")
     */
    protected $date;

    /**
     * @var Entity1
     * @ORM\ManyToOne(targetEntity="Entity1", inversedBy="entity2", fetch="EAGER")
     */
    protected $entity1;
}

tables and data

entity1:

id name
1 Jhon
2 Clare

entity2:

id date entity1_id
1 2011-01-01 00:00:01 1
2 2012-02-02 00:00:02 1
3 2013-03-03 00:00:03 2
4 2014-04-04 00:00:04 2

my query builder

use Doctrine\ORM\EntityRepository;

class Entity1Repository extends EntityRepository
{
    public function getData()
    {
        $qb = $this
            ->createQueryBuilder('Entity1')
            ->select('Entity1, Entity2.date')
            ->join('Entity1.entity2', 'Entity2', Join::WITH, 'Entity2.date > :date')
            ->setParameter('date', '2000-01-01 00:00:01')
        ;
        $result1 = $qb->getQuery()->getArrayResult(); // HYDRATE_ARRAY
        $result = $qb->getQuery()->getResult(); // HYDRATE_OBJECT
        
//        return $result1;
//        return $result2;
    }
}

proper result is this:

id name date
1 Jhon 2011-01-01 00:00:01
1 Jhon 2012-02-02 00:00:02
2 Clare 2013-03-03 00:00:03
2 Clare 2014-04-04 00:00:04

what is happening

$result1 = $qb->getQuery()->getArrayResult(); // HYDRATE_ARRAY

is really returning proper number of rows

BUT and here comes the BUG finally:

$result2 = $qb->getQuery()->getResult(); // HYDRATE_OBJECT

is returning just 2 rows:

id name date
1 Jhon 2011-01-01 00:00:01
2 Clare 2013-03-03 00:00:03

this is because somehow entities are made unique.

my workaround

as a workaround, what i have to do is, to exectute 2 queries. 1st to get just Entity1.ids joined with Entity2.dates by using `getArrayResult()`
and second query to get Entity1 objeces by unique ids from 1st query.
and than manualy join those results in php.



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

I see that you are using Join::WITH, but not providing a conditional in the example. Are you filtering a fetch-joined association?

Comment by gondo [ 23/Jul/14 ]

sorry i've tried to simplify my structure as much as it was possible, there are actually real conditions, one of them is date condition (among many others). i've updated my code

Comment by Marco Pivetta [ 23/Jul/14 ]

There are still some inconsistencies in the issue - where is that query parameter used, for example?

Comment by gondo [ 23/Jul/14 ]

im using it in EntityRepository (sorry, didnt know thats important) i ll update my code
and the whole code is in Symfony2 project (web and command line applications)

Comment by Marco Pivetta [ 23/Jul/14 ]

What I mean is that in

->setParameter('date', new \DateTime('last month'))

, parameter :date does not exist in the DQL.

Comment by gondo [ 23/Jul/14 ]

i see, sorry its part of JOIN condition, i've updated the code





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

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

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

Linux Ubuntu 13.10 / PHP 5.5.3 / Mysql 5.5.x



 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






[DDC-3222] PostUpdate event destroying collectionUpdates Created: 21/Jul/14  Updated: 21/Jul/14

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

Type: Bug Priority: Critical
Reporter: Jacob Spizziri Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Mac OSX, AMP, php 5.3.27



 Description   

I have an entity that contains a Many-To-Many Unidirectional association. When the association is updated and the entity is flushed the changes are not being persisted to the database.

This is because the postUpdate event is being fired on executeUpdates, which is being called before the collection updates are being processed here:

            // Collection updates (deleteRows, updateRows, insertRows)
            foreach ($this->collectionUpdates as $collectionToUpdate) {
                $this->getCollectionPersister($collectionToUpdate->getMapping())->update($collectionToUpdate);
            }

This is occurring in UnitOfWork->commit() lines 333 through 366.

Apparently the postUpdate listener I wrote was causing the collectionUpdates property to be erased.



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

What does the listener actually do? Doesn't look like a bug to me...

Comment by Jacob Spizziri [ 21/Jul/14 ]

I'm using FOSElasticaBundle/ElasticSearch. On the postUpdate event I'm calling fos:elastica:populate on the entity indexes. Heres the code

<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

namespace SRC\Bundle\SearchBundle\EventListener;

use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
use Doctrine\ORM\Event\LifecycleEventArgs;
use SRC\Bundle\ProductBundle\Entity\Product;
use SRC\Bundle\UserBundle\Entity\User;

/**
 * Description of SearchIndexer
 *
 * @author jacobspizziri
 */
class SearchIndexer
{	
	protected $container;
	protected $logger;
	
	public function __construct($container, $logger) {
		$this->container = $container;
		$this->logger = $logger;
	}
	
	
	public function postUpdate(LifecycleEventArgs $args){
		$this->index($args);
	}
	
	protected function index($args){
		$entity = $args->getEntity();

		$arguments = false;
		$command = new \FOS\ElasticaBundle\Command\PopulateCommand();
		$command->setContainer($this->container);
		
		//TODO: probably need to specify the --env=prod/dev
		// update Elastica on Product update
		if ($entity instanceof Product) {
			$this->logger->info('Updating Product Search Indexes');
			
			$arguments = array(
					'--index'=>'website',
					'--type' => 'product'
					);
		} else if ($entity instanceof User) {
			$this->logger->info('Updating User Search Indexes');

			$arguments = array(
					'--index'=>'website',
					'--type' => 'user'
					);
		}
		
		
		if($command && $arguments){
			$input = new ArrayInput($arguments);
			$output = new NullOutput();
			
			$result = $command->run($input, $output);
			$this->logger->info('Finished Updating Search Indexes with result: '. strval($result));
		}
	}
}
?>

Am I using this event incorrectly? Should I only be using postPersist?





[DDC-3221] Invalid binding for primary key of entity relation Created: 21/Jul/14  Updated: 21/Jul/14

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

Type: Bug Priority: Major
Reporter: Alexandr Smaga Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: orm


 Description   

Hello.

We use doctrine2 ORM with doctrine/doctrine-bundle in our symfony2 based project. We developed functionality which is similar to some kind of import process.

And we have an issue that appears from time to time in different points during the import.

Issue is following:
Lets imagine we have 3 entities Account, Contact, Contact Address.
Account has many to one relation on contact and contact has one to many relation on contact address.

Our import creates all 3 entities and persist only Account, contact and address are persisted via cascade persist.
We have writer that contains following code

    public function write(array $items)
    {
        try {
            $this->entityManager->beginTransaction();
            foreach ($items as $item) {
                $this->entityManager->persist($item);
            }
            $this->entityManager->commit();
        } catch (\Exception $exception) {
            $this->entityManager->rollback();

            throw $exception;
        }
        $this->entityManager->flush();
        $this->entityManager->clear();
    }

So we clear EntityManager for each batch in order to avoid high memory consumption.
Import fails during different entities insert, but errors are very similar.
Example of error is

> [error] An exception occurred while executing 'INSERT INTO ... VALUES (?, ?, ?, ?, ?)' with params ["__start__", "2014-07-21 00:55:35", 0, null, 21]:
>
> SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`DB`.`account`, CONSTRAINT `FK_B3D57B301023C4EE` FOREIGN KEY (`contact_id`) REFERENCES `contact` (`id`) ON DELETE CASCADE)

After debugging I found that problem is in BasicEntityPersister#prepareUpdateData

$uow->getEntityIdentifier($newVal);


returns oid that is real one, but UOW contains not the same ID as in $newVal entity. It seems like spl_object_hash duplicates oid.

Any help is appreciated.
Thanks in advance.






[DDC-3220] Association mappings of embedded class not loaded into entity classMetadata Created: 21/Jul/14  Updated: 21/Jul/14

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

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


 Description   

method inlineEmbeddable from Doctrine\ORM\Mapping\ClassMetadataInfo mapped only columns, but relations is omitted






[DDC-3219] Ensure PersistentCollection->count() is of type int Created: 21/Jul/14  Updated: 21/Jul/14

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

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

SQL Server 2012



 Description   

https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/PersistentCollection.php#L566-L577 does not always return an int. How do i know this? because i compare this count with a php count() with strict checking.

If ($collection->count() !== count($somethingElse))

{ throw new Exception($collection->count() . ' is different then ' . count($somethingElse)); }

and at one time this message showed: 3 is different then 3



 Comments   
Comment by Flip [ 21/Jul/14 ]

My colleague told me that it was his mistake somehow, so i don't know how valid this really is !!!





[DDC-3218] Argument 3 passed to Doctrine\ORM\Event\PreUpdateEventArgs::__construct() must be of the type array, null given Created: 18/Jul/14  Updated: 18/Jul/14

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

Type: Bug Priority: Major
Reporter: Grégoire Pineau Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Linux / Mint 15
php 5.5.*



 Description   

Argument 3 passed to Doctrine\ORM\Event\PreUpdateEventArgs::__construct() must be of the type array, null given, called in /home/greg/dev/product/insight/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 1009 and defined

Stack trace:

[1] PHPUnit_Framework_Error: Argument 3 passed to Doctrine\ORM\Event\PreUpdateEventArgs::__construct() must be of the type array, null given, called in /project/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 1009 and defined
at n/a
in /project/vendor/doctrine/orm/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php line 47

at PHPUnit_Util_ErrorHandler::handleError('4096', 'Argument 3 passed to Doctrine\ORM\Event\PreUpdateEventArgs::__construct() must be of the type array, null given, called in /project/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 1009 and defined', '/project/vendor/doctrine/orm/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php', '47', array('entity' => object(Violation), 'em' => object(EntityManager)))
in /project/vendor/doctrine/orm/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php line 47

at Doctrine\ORM\Event\PreUpdateEventArgs->__construct(object(Violation), object(EntityManager), null)
in /project/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 1009

at Doctrine\ORM\UnitOfWork->executeUpdates(object(ClassMetadata))
in /project/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 341

at Doctrine\ORM\UnitOfWork->commit(null)
in /project/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php line 389

at Doctrine\ORM\EntityManager->flush()
in /project/src/SensioLabs/Bundle/MyBundle/Controller/MyController.php line 127

at SensioLabs\Bundle\MyBundle\Controller\MyController->ignoreAction(object(Request), object(Project), object(Analysis), '4')
in line

at call_user_func_array(array(object(MyController), 'ignoreAction'), array(object(Request), object(Project), object(Analysis), '4'))
in /project/app/bootstrap.php.cache line 1043

at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), '1')
in /project/app/bootstrap.php.cache line 1015

at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), '1', true)
in /project/app/bootstrap.php.cache line 1154

at Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel->handle(object(Request), '1', true)
in /project/app/bootstrap.php.cache line 435

at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
in /project/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Client.php line 81

at Symfony\Component\HttpKernel\Client->doRequest(object(Request))
in /project/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Client.php line 111

at Symfony\Bundle\FrameworkBundle\Client->doRequest(object(Request))
in /project/vendor/symfony/symfony/src/Symfony/Component/BrowserKit/Client.php line 319

at Symfony\Component\BrowserKit\Client->request('POST', '/projects/id-foo/analyses/2/rule/4/ignore', array('ignore_rule' => array('comment' => 'Message about why this rule has been ignored', '_token' => 'CxEFTSv4GZQSWYXtRt-eHybaML4z8I0WK1DHiwr8Ih0')))
in /project/src/SensioLabs/Bundle/MyBundle/Test/Client.php line 489

at SensioLabs\Bundle\MyBundle\Test\Client->ignoreRuleViolations('id-foo', '2', '4', false)
in /project/src/SensioLabs/Bundle/MyBundle/Tests/Acceptance/ViolationCommentsTest.php line 217

at SensioLabs\Bundle\MyBundle\Tests\Acceptance\ViolationCommentsTest->testDashboardWithCriticalIgnoredRules()
in line

at ReflectionMethod->invokeArgs(object(ViolationCommentsTest), array())
in /project/vendor/phpunit/phpunit/src/Framework/TestCase.php line 951

at PHPUnit_Framework_TestCase->runTest()
in /project/vendor/phpunit/phpunit/src/Framework/TestCase.php line 817

at PHPUnit_Framework_TestCase->runBare()
in /project/vendor/phpunit/phpunit/src/Framework/TestResult.php line 686

at PHPUnit_Framework_TestResult->run(object(ViolationCommentsTest))
in /project/vendor/phpunit/phpunit/src/Framework/TestCase.php line 753

at PHPUnit_Framework_TestCase->run(object(PHPUnit_Framework_TestResult))
in /project/vendor/phpunit/phpunit/src/Framework/TestSuite.php line 675

at PHPUnit_Framework_TestSuite->run(object(PHPUnit_Framework_TestResult))
in /project/vendor/phpunit/phpunit/src/TextUI/TestRunner.php line 426

at PHPUnit_TextUI_TestRunner->doRun(object(PHPUnit_Framework_TestSuite), array('listGroups' => false, 'loader' => null, 'useDefaultConfiguration' => true, 'configuration' => '/project/app/phpunit.xml.dist', 'filter' => 'testDashboardWithCriticalIgnoredRules', 'testSuffixes' => array('Test.php', '.phpt')))
in /opt/dotfiles/vendor/phpunit/phpunit/PHPUnit/TextUI/Command.php line 176

at PHPUnit_TextUI_Command->run(array('/usr/local/bin/phpunit', 'c', 'app/', '-filter', 'testDashboardWithCriticalIgnoredRules', 'src/SensioLabs/Bundle/MyBundle/Tests/Acceptance/ViolationCommentsTest.php'), true)
in /opt/dotfiles/vendor/phpunit/phpunit/PHPUnit/TextUI/Command.php line 129

at PHPUnit_TextUI_Command::main()
in /opt/dotfiles/vendor/phpunit/phpunit/composer/bin/phpunit line 63

I fails in this code

    private function executeUpdates($class)
    {
        $className          = $class->name;
        $persister          = $this->getEntityPersister($className);
        $preUpdateInvoke    = $this->listenersInvoker->getSubscribedSystems($class, Events::preUpdate);
        $postUpdateInvoke   = $this->listenersInvoker->getSubscribedSystems($class, Events::postUpdate);

        foreach ($this->entityUpdates as $oid => $entity) {
            if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
                continue;
            }

            if ($preUpdateInvoke != ListenersInvoker::INVOKE_NONE) {
// => this line
                $this->listenersInvoker->invoke($class, Events::preUpdate, $entity, new PreUpdateEventArgs($entity, $this->em, $this->entityChangeSets[$oid]), $preUpdateInvoke);
                $this->recomputeSingleEntityChangeSet($class, $entity);
            }

            if ( ! empty($this->entityChangeSets[$oid])) {
                $persister->update($entity);
            }

            unset($this->entityUpdates[$oid]);

            if ($postUpdateInvoke != ListenersInvoker::INVOKE_NONE) {
                $this->listenersInvoker->invoke($class, Events::postUpdate, $entity, new LifecycleEventArgs($entity, $this->em), $postUpdateInvoke);
            }
        }
    }


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

Requires a test case





[DDC-3215] wrong quotation Created: 16/Jul/14  Updated: 17/Jul/14

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

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


 Description   

when doctrine build query´s, for example when you doing

$entitity->getTest()->clear();

following queries are generated (test_id is integer in mysql):

DELETE FROM test WHERE test_id = '6'

Is this right?
For me the right query would be:

DELETE FROM test WHERE test_id = 6

as in http://dev.mysql.com/doc/refman/5.5/en/type-conversion.html
6 will be converted to float, this can be an issue, or?

Comparisons that use floating-point numbers (or values that are converted to floating-point numbers) are approximate because such numbers are inexact. This might lead to results that appear inconsistent:

mysql> SELECT '18015376320243458' = 18015376320243458;
        -> 1
mysql> SELECT '18015376320243459' = 18015376320243459;
        -> 0

this also happens in dql sometimes, why doctrine does this not automatic right due to description in the entities?

     /**
     * @ORM\Id @ORM\Column(type="integer")
     * @ORM\GeneratedValue
     */


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

Could you please convert this to a failing test case? Doctrine doesn't quote integers as strings by default.

Comment by revrev [ 16/Jul/14 ]

i try to describe what i have done

i have an Entity with:

    /**
     * @ORM\ManyToMany(targetEntity="Messen", inversedBy="vertrag_messen")
     * @ORM\JoinTable(name="vertrag_messen")
     **/
    private $vertrag_messen;

    public function __construct()
    {
        $this->vertrag_messen = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function getMessen()
    {
        return $this->vertrag_messen;
    }

when i now clear the Data

$entitity->getMessen()->clear();

following query is created
DELETE FROM vertrag_messen where messe_id = '6'

Should here not set the value 6 as integer (param_int) (DELETE FROM test vertrag_messen where messe_id = 6) that mysql doesn´t have to cast the value? (http://dev.mysql.com/doc/refman/5.5/en/type-conversion.html) or is this not an problem?

Comment by Marco Pivetta [ 16/Jul/14 ]

is messe_id in your entity an integer or a string at the moment in time when that query is being executed?

Comment by revrev [ 16/Jul/14 ]

the value comes automatic
$entitity = $em->getRepository('Base\Entities\Vertrag')>find(intval($data["id"]));

i don´t set messe_id here

Comment by Marco Pivetta [ 16/Jul/14 ]

Can you var_dump the Base\Entities\Messe instance?

Comment by revrev [ 16/Jul/14 ]

object(stdClass)#1014 (64) {
["__CLASS__"]=>
string(24) "Base\Entities\Vertrag"
["id"]=>
int(6)
[„vertrag_messen"]=>
array(1)

Unknown macro: { [0]=> string(20) "BaseEntitiesMessen" }


["erstellungsdatum"]=>
object(stdClass)#1210 (3)

Unknown macro: { ["__CLASS__"]=> string(8) "DateTime" ["date"]=> string(25) "2013-09-28T00}

["zeitraumvon"]=>
NULL
["zeitraumbis"]=>
NULL
["jahr"]=>
int(2014)
["created"]=>
object(stdClass)#1178 (3)

Unknown macro: { ["__CLASS__"]=> string(8) "DateTime" ["date"]=> string(25) "2013-09-28T19}

["updated"]=>
object(stdClass)#1177 (3)

Unknown macro: { ["__CLASS__"]=> string(8) "DateTime" ["date"]=> string(25) "2014-07-16T17}

["uuid"]=>
string(36) "52470c58-4288-45eb-b75f-0c41c0a81437"
}

Comment by Marco Pivetta [ 17/Jul/14 ]

yeah, integer identifier there.
Could you verify if the problem also comes up with current master? I think this issue is related with another one that was fixed some months ago in 2.5.x-dev





[DDC-2953] ArrayHydrator: Not all items hydrated while orderBy Created: 05/Feb/14  Updated: 14/Jul/14

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

Type: Bug Priority: Critical
Reporter: Mariusz Jaskółka Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: array, hydration
Environment:

Linux and Windows, PHP5


Attachments: File ArrayHydrator.php     File Array_Hydrator_4.2.php     File Array_hydrator_4.2_bugfix.php    

 Description   

I will explain the problem using example and pseudo-code:

I have query like that:
SELECT (...) FROM order LEFT JOIN person LEFT JOIN identifier (...) order by (...)

The rows returned by query are following (the order is very important):
order_id|person_id|identifier_id|
12 |21 |33 |
12 |21 |34 |
11 |21 |35 |
11 |21 |33 |
11 |21 |34 |
12 |21 |35 |

After hydration the result is like:
result[0][person][identifier][0][id]=33
result[0][person][identifier][0][id]=34
result[1][person][identifier][0][id]=35
result[1][person][identifier][0][id]=34

But it should be:
result[0][person][identifier][0][id]=33
result[0][person][identifier][0][id]=34
result[0][person][identifier][0][id]=35
result[1][person][identifier][0][id]=35
result[1][person][identifier][0][id]=34
result[1][person][identifier][0][id]=33

The reason is that ArrayHydrator::_identifierMap contains only object id and parents object id. In may example there is difference in parents parent (grandparent) id.



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

I've started work on this at https://github.com/doctrine/doctrine2/pull/933

Comment by Mariusz Jaskółka [ 06/Feb/14 ]

This is how I temporary solved the issue, maybe it can help (attachment).

Comment by Marco Pivetta [ 06/Feb/14 ]

Mariusz Jaskółka can you provide a diff with current master? This seems to be based off 2.3 or previous versions...

Comment by Mariusz Jaskółka [ 06/Feb/14 ]

Version 2.4.2 oryginal file and bugfix

Comment by Mariusz Jaskółka [ 06/Feb/14 ]

Oh sorry it is version 2.4.1 (composer downloaded that version for me).
I hope it will be ok.

Comment by Marco Pivetta [ 06/Feb/14 ]

Mariusz Jaskółka thanks! I'm trying it right now

Comment by Mariusz Jaskółka [ 06/Feb/14 ]

I added one dimention to $this->_identifierMap to be sure that all object's children's keys will be mapped separately.

Comment by Marco Pivetta [ 06/Feb/14 ]

Mariusz Jaskółka, I've applied your hotfix at https://github.com/doctrine/doctrine2/commit/c05921032ff6947daca2d7275031e5cde4700634 and the tests seem to pass on my system and on travis. You may want to check it out and see if it works for your use case.

Comment by Mariusz Jaskółka [ 06/Feb/14 ]

It works for my use case correctly. You apparently forgot to remove/comment line 82 which is not necessary now.

Comment by Marco Pivetta [ 06/Feb/14 ]

Mariusz Jaskółka fixed, thanks!

Comment by Marco Pivetta [ 14/Jul/14 ]

I don't think we'll have a fix for this issue for 2.5, as it will probably require a complete rewrite of the array hydrator

Comment by Guilherme Blanco [ 14/Jul/14 ]

... and introducing BC breaks.





[DDC-3212] Remove ArrayHydrator logic Created: 14/Jul/14  Updated: 14/Jul/14

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

Type: Improvement Priority: Critical
Reporter: Marco Pivetta Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: hydration, hydrator


 Description   

The Doctrine\ORM\Internal\Hydration\ArrayHydrator ( https://github.com/doctrine/doctrine2/blob/85fbf684363b932a4ebaf543ef059f9ee1e512b0/lib/Doctrine/ORM/Internal/Hydration/ArrayHydrator.php ) is currently very messy and complicated due to the lack of actual Doctrine\ORM\UnitOfWork references when working with it, since we are not dealing with objects.

In order to reduce the amount of bugs and code duplication when working with array hydration, I would simply suggest making use of the Doctrine\ORM\Internal\Hydration\ObjectHydrator ( https://github.com/doctrine/doctrine2/blob/85fbf684363b932a4ebaf543ef059f9ee1e512b0/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php ) and its siblings, and then extracting data coming from the results in it as an array.

This could be a simple reflection-based extraction (pseudo):

class ArrayHydrator
{
    public function hydrateAllData()
    {
        foreach ($this->objectHydrator->hydrateAllData() as $object) {
            yield $this->extractData($object);
        }
    }
}

The point here is that array-based hydration is not the primary focus of the ORM, and users should probably rely on SQL only when they want array hydration.



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

Note: performance is one of our biggest requirements, and array hydration is meant to achieve that. As I stated above, plain SQL is probably better for this sort of operation, so the issue is more about deprecating the ArrayHydrator completely, providing utilities to manipulate SQL resultsets instead.





[DDC-2767] ID property of MayToOne association has wrong type Created: 30/Oct/13  Updated: 14/Jul/14

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

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


 Description   

I'm seeing the following behaviour in some Doctrine code I'm writing:

$entity = array_pop($qb->getQuery()->getResult());
echo gettype($entity->getId()) . ' ' . $entity->getId();
// prints: integer 123

$association = $entity->getAssociation(); // unidirectional ManyToOne link to some other entity
echo gettype($association->getId()) . ' ' . $association->getId();
// prints: string 345

When I load the associated entity directly (via find() f.x.), it's ID has the integer type as expected, and the database structure looks correct, too.

I'm not entirely sure if this is a problem in my code or some issue in QueryBuilder or some other Doctrine component, but if someone could point me into the right direction, that would really be helpful.

I guess normally the type of the ID is not so important because you're not supposed to access it directly anyways, but I need to provide backward compatibility for a lot of code written against a different ORM API that provided exactly this behaviour.



 Comments   
Comment by flack [ 07/Nov/13 ]

After some research, the problem sounds kind of similar to

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

only that in my case, it's not a custom type, but a builtin one that is not working. But AFAICT, in both cases it's getting the ID from a proxy that is problematic

Comment by Doctrine Bot [ 14/Jul/14 ]

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





[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-1988] Add Any and ManyToAny annotations Created: 18/Aug/12  Updated: 10/Jul/14

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

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


 Description   

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






[DDC-3062] [GH-997] [FIX] Allow to use ManyToMany with all operators Created: 31/Mar/14  Updated: 08/Jul/14

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

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


 Description   

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

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

Message:

Hi,

ping @guillhermoblanco : I think this may be blocking for 2.5

I introduced not so long ago support for ManyToMany for Criteria. However, I realized my implementation was really incomplete, because I hard-coded the "=" operator (https://github.com/doctrine/doctrine2/pull/885/files#diff-982b7374bbe9d5f4b6b71f4869a446eaR575). This means that it fails in a lot of cases when you use something different than "eq" for Criteria.

This PR fixes that, however it's a bit hacky. The SqlExpressionVisitor was made by type hinting for a BasicEntityPersister, preventing us from using us for a collection persister. Therefore I added a new interface to keep BC.

There is also a lot of code duplication (the whole "getSelectConditionSQL" was copied from the BasicEntityPersister), but without trait or BC, I have no idea about how to solve it.

All tests pass, test were added for other operators.






[DDC-2332] [UnitOfWork::doPersist()] The spl_objact_hash() generate not unique hash! Created: 05/Mar/13  Updated: 08/Jul/14

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

Type: Bug Priority: Major
Reporter: Krisztián Ferenczi Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Symfony 2.1.8, php 5.4.7 and php 5.4.12, Windows 7


Attachments: Text File hashlogs.txt    

 Description   

I created fixtures and some data was inserted many times without calling the Task entity PrePersist event listener.

I printed the used and generated hash and I saw a Proxies_CG_\Asitly\ProjectManagementBundle\Entity\User hash equal a Task entity hash!



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

Please provide either a code example or a test case. As it stands, this issue is incomplete

Comment by Benjamin Eberlei [ 05/Mar/13 ]

Are you calling EntityManager#clear() inbetween? Because PHP reuses the hashes. The ORM accounts for this.

Comment by Benjamin Eberlei [ 05/Mar/13 ]

This is not a reproduce case, i don't want to execute your whole project.

I want to know, what is the actual bug that you see? Can you just print a list of all the hashes? Because the hashes dont differ at the end, bu tjust somewhere in the middle.

Comment by Krisztián Ferenczi [ 05/Mar/13 ]

I attached a hashlogs.txt file. The last Task class hash is 0000000050ab4aba0000000058e1cb12 ( line 3 129 )

This is not unique, view the line 2 760 . The Task is not being saved and the program don't call the prePersist listener. The "UnitOfWork" believe the entity has been saved because the isset($this->entityStates[$oid]) is true. But it is an other entity.

Comment by Krisztián Ferenczi [ 06/Mar/13 ]

The EntityManager::clear() fix the problem, but this is not "good" and "beautiful" solution. Shows no sign of that conflicts were and this is causing the problem. I was looking for the problem 7 hours.

Comment by Marco Pivetta [ 26/Jun/14 ]

One possible issue here is that a listener registers an entity as managed while a proxy is being loaded.

The given data is still insufficient to actually verify the problem.





[DDC-3206] Possible to remove inversedBy (use only mappedBy)? Created: 05/Jul/14  Updated: 07/Jul/14

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

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


 Description   

Hi guys!

This is another developer experience situation. Here is the flow:

1. I setup the owning side of a relationship (let's use ManyToMany, the hardest one for this)

2. Later, I decide to setup the inverse side of the relationship. When I do this, I of course add the `mappedBy` attribute so that it points to the exact property/relationship we're dealing with

3. Then, I also need to go back to the owning side and add `inversedBy`.

Why is step 3 (inversedBy) needed? Isn't this redundant information, since the `mappedBy` fully maps out that these 2 associations form different sides of the same relationship? I would love to remove this, I hate explaining to people starting with relationships to now go back to the main entity to add this key. It feels like duplication, which I think people sense.

Of course, I very well may be wrong and it may be needed .

Thanks!



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

I'd suggest doing the opposite: dropping mappedBy.

I'm not sure why JPA introduced this sort of bidirectional mapping, but for practical purposes, it makes it possible for us to load metadata for associations on both sides of the associations. Without having both mappedBy and inversedBy we'd be forced to scan through all existing mappings to find which pieces of the jigsaw fit together.

I don't think we have a good solution for this except for a "build mappings" step that warms up a cache, and that's a very radical architectural change that we can only introduce in 3.x

Comment by Maxime Veber [ 07/Jul/14 ]

Hi, please excuse me if what I say is wrong and do not hesitate to correct me, it's my first immertion in Doctrine code .

So I checked a little bit the situation in the code. I don't see the problem dropping inversedBy. It's easier understandable for the final user.
In facts right now the ManyToMany work very well with only `mappedBy` options so the `invertedBy` is clearly a duplicated information.

The problem for the implementation of this feature is that the ownerSide is decided by a single method for every mappings, so she's quite complexe. So the method decide only on using `mappedBy` and `invertedBy`. This behavior should be modifiable without too much troubles.

https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php#L1353

But another problem here is that should be discuss is that it's a big BC Break.





[DDC-3164] [GH-1057] Add failing test for DDC-3160 Created: 12/Jun/14  Updated: 06/Jul/14

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

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


 Description   

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

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

Message:

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



 Comments   
Comment by Doctrine Bot [ 06/Jul/14 ]

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

Comment by Doctrine Bot [ 06/Jul/14 ]

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





[DDC-3197] [GH-1074] [DDC-3160] Alternate fix for DDC-2996 bug Created: 26/Jun/14  Updated: 06/Jul/14

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

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


 Description   

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

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

Message:

The fix implemented for DDC-2996 seems to have broken quite a bit of code outside of Doctrine (for instance, the popular DoctrineExtensions project).

I'm not too well versed in Doctrine internals, but looking at the fix, I found it odd that an entity would live in both the insertion and update tracking in the unit of work.

This implementation should fix the case described in DDC-2996, while not creating any side effects with objects that are scheduled to be inserted.

I've ran this test with the Doctrine test suite and have also tested this change with the DoctrineExtensions project; unless I'm doing something wrong, it seems to have good results.

Again, I'm not too well versed in the inner workings of Doctrine, but I did a little research, poked around some code, and came up with this.



 Comments   
Comment by Doctrine Bot [ 06/Jul/14 ]

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

Comment by Doctrine Bot [ 06/Jul/14 ]

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





[DDC-3205] [DX] Interactive Management Command Created: 05/Jul/14  Updated: 06/Jul/14

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

Type: New Feature Priority: Minor
Reporter: Ryan Weaver Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Hi guys!

This is part of the Symfony Developer Experience Initiative, which I hope can help Doctrine as well . This is a vision for a console tool to help visualize and manage your Doctrine entities. There are so many options and configuration that I think sometimes either (A) people don't even realize what options are available to them or (B) it's difficult to set everything up correctly (especially with relationships).

Imagine an interactive command that did things like:

  • listed your entities
  • listed fields in your entities (and their options, nullable, unique, etc)
  • Allowed you to change field options (e.g. change a field from nullable true to false
  • Allowed you to see your relationships and change options (cascade, JoinColumn stuff, etc)
  • Allowed you to setup relationships or setup the inverse side of a one-sided relationship
  • Added getters/setters
  • Generated helper methods into repositories (e.g. a method to create a query builder that joins a Product over to ProductImages after creating that relationship).

Does anyone see any issues with this? Obviously, this is HUGE, but it wouldn't need to start huge - it could start simply with some visualization and move from there. I think this could bring down the barrier to entry tremendously, and offer (via generation and visualization) some of the benefits of AR magic without that darn magic .

Thanks!



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

TL;DR: dumping details, yes please! modifying files/mappings, no-go.

A couple of things here:

  • listing entities is already available, see orm:info
  • listing all fields and additional details may be useful as an addition to orm:info via a flag. Implementation is also trivial
  • changing mappings via CLI - I'm really against this proposal. I've already tried getting rid of anything codegen-related from the symfony documentation, and I would not want codegen to land in the ORM. Mappings may come from annotations, from xml configs, from yaml or plain PHP files. They may also be processed by listeners and look completely different from the file counterparts. No, let's stay away from any ORM-driven mapping modification.
  • adding getters/setters, generating repositories, adding fields/associations: Doctrine's codegen is actually ONLY meant to provide an easy migration from a legacy DB to ORM entities+mappings, and we're also trying to get away from it in core.

Note that for mappings there's http://www.pulpo18.com/, which eases the path for newcomers. I also developed something for the ZF2 packages (which I must move to a separate library), see http://stackoverflow.com/a/14574952/347063





[DDC-3203] "Orphan Removal" for ManyToMany and "Cascade remove" doesn't trigger "preRemove" callback on related entity Created: 01/Jul/14  Updated: 02/Jul/14

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

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

Latest ZendFramework2, latest ZF2 DoctrineModule and latest ZF2 DoctrineORMModule



 Description   

I'm not sure if it's me, but I couldn't get "preRemove" callback/event working when "remove" action is triggered from related entity, but it works where the entity itself (the one with "preRemove" event) is removed directly.

According to documentation:
"If an association is marked as CASCADE=REMOVE Doctrine 2 will fetch this association. If its a Single association it will pass this entity to ´EntityManager#remove()`"....and similar for multiple entities.
DOC: http://doctrine-orm.readthedocs.org/en/latest/reference/working-with-objects.html?highlight=working-with-objects%20removing-entities#removing-entities

"preRemove event is called on every entity when its passed to the EntityManager#remove()"
DOC: http://docs.doctrine-project.org/en/latest/reference/events.html#preremove

So according to documentation "preRemove" should get triggered on "cascade remove", but it doesn't get in my case. Is this normal behavior or a bug?

I'm not sure if it the problem might be in any of ZF2 modules, but I've decided to post the issue here, since I'm referring to documentation of this project.

Beside that I've also noticed that "orphan removal" doesn't work on ManyToMany, although documentation says that it's supported (on IRC they've said that it may be a bug in documentation, that it is not really yet supported...they found no code changes when documentation was changed).
DOC:
http://docs.doctrine-project.org/en/latest/reference/working-with-associations.html#orphan-removal






[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-3200] [GH-1077] Support filter parameters in Configuration Created: 01/Jul/14  Updated: 01/Jul/14

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

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


 Description   

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

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

Message:

Based on work done in doctrine/mongodb-odm#908

My understanding is that this makes it easier to setup filters at boot time, instead of having to fetch them from the collection later on.

For added context, the related PR from MongoDB ODM's Symfony bundle is doctrine/DoctrineMongoDBBundle#255






[DDC-1970] DiscriminatorMap recursion when using self-reference Created: 06/Aug/12  Updated: 01/Jul/14

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

Type: New Feature Priority: Major
Reporter: Krzysztof Kolasiak Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 2
Labels: None


 Description   

I've ran into a problem with self-referencing entity. When fetching an entity, recursion occurs, fetching every related entity defined by ManyToOne relation
(in this example $sponsor), ignoring LAZY or EXTRA_LAZY fetch mode - it executes numerous queries.

/**
 * @ORM\Entity(repositoryClass="Acme\Bundle\UserBundle\Entity\Repository\UserRepository")
 * @ORM\Table(name="f_user")
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="type", type="string")
 * @ORM\DiscriminatorMap({"user_person" = "UserPerson", "user_company" = "UserCompany"})
 */
abstract class UserBase extends FOSUser

/* .... */

    /**
     * @var UserBase
     *
     * @ORM\OneToMany(targetEntity="UserBase", mappedBy="sponsor")
     */
    protected $referrals;

    /**
     * @ORM\ManyToOne(targetEntity="UserBase", inversedBy="referrals")
     * @ORM\JoinColumn(name="sponsor_id", referencedColumnName="id")
     */
    protected $sponsor;



 Comments   
Comment by Alexander [ 14/Aug/12 ]

I have changed this into a feature request because you have hit the limitations of using inheritance and self referencing entities.

Doctrine2 cannot currently lazy load UserBase#$sponsor because we don't know which proxy we have to insert. It can either be UserPerson or UserCompany. In order to know this Doctrine2 has to query the actual object to determine its type. The current strategy is then to load the actual entity because we have all data anyway.

In order to implement this feature we need to insert a proxy instead of the actual entity. If we do that there should be no recursion happening.

Comment by Marco Pivetta [ 21/Feb/13 ]

Reduced priority

Comment by Prathap [ 10/May/13 ]

It'd be great if this is a configurable option.

Comment by Kevin Bond [ 01/Jul/14 ]

I have also run into this.





[DDC-2364] [GH-625] [DDC-2363] Duplicated record with orphanRemoval and proxy Created: 22/Mar/13  Updated: 30/Jun/14

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

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

Issue Links:
Duplicate
duplicates DDC-2363 Duplicated record with orphanRemoval ... Awaiting Feedback

 Description   

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

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

Message:

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



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

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





[DDC-3188] Call to a member function getValue() on a non-object in vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php Created: 24/Jun/14  Updated: 27/Jun/14

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

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

PHP 5.4.11
opensuse
apache2



 Description   

This is the line that causes the fatal error: https://github.com/doctrine/doctrine2/blob/v2.4.2/lib/Doctrine/ORM/UnitOfWork.php#L678

This is the association that is breaking it (i.e. reflFields[ 'user' ] is a non-object):

Tweet.php
/**
 * @ManyToOne(targetEntity="User")
 * @JoinColumn(name="user_id", referencedColumnName="id")
 *
 * @var User
 */
protected $user;

This is the pk of the referenced entity.

User.php
/**
 * @Id
 * @Column(name="id", type="bigint", nullable=false)
 *
 * @var int
 */
protected $id;

If an exception was thrown due to missing metadata information, I could catch it, but fatal errors due to this bug have been crashing our scripts and they've had to be manually restarted.

Let me know what other information is needed.

Full stack trace:

PHP 5. Doctrine\ORM\EntityManager->flush() our_code.php
PHP 6. Doctrine\ORM\UnitOfWork->commit() vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:389
PHP 7. Doctrine\ORM\UnitOfWork->computeChangeSets() vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:297
PHP 8. Doctrine\ORM\UnitOfWork->computeScheduleInsertsChangeSets() vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:703
PHP 9. Doctrine\ORM\UnitOfWork->computeChangeSet() vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:404
PHP Fatal error: Call to a member function getValue() on a non-object in vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 678



 Comments   
Comment by Marco Pivetta [ 24/Jun/14 ]

Did you actually validate your mappings?

Comment by Daniel Imhoff [ 24/Jun/14 ]

I did not validate the mapping. I did not know about the orm:validate-schema until just now. I will fix these errors and resubmit if there is still an issue.

Sorry about that, thanks.

Comment by Daniel Imhoff [ 24/Jun/14 ]

The tweet and user relationship is not in the list of invalid mappings.

Comment by Marco Pivetta [ 26/Jun/14 ]

Are User and Tweet in the same namespace?

Comment by Daniel Imhoff [ 27/Jun/14 ]

Yes, and I've since then used the FQNS. I would get a class not found error when validating schema.
This is something that I know can't really be debugged by you guys, I was just hoping for a little direction. We are using memcache to store our metadata, and we are clearing and regenerating the metadata during every deploy (it is not autogenerated). I'm now using a commit hash as the namespace of the metadata, so we'll see if this fixes the issue.

Comment by Marco Pivetta [ 27/Jun/14 ]

It looks like a typo (CasESensiTIViTy issue) to me.





[DDC-213] Persist order of collections Created: 15/Dec/09  Updated: 27/Jun/14

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

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

Issue Links:
Duplicate
is duplicated by DDC-181 Order of many-to-many relationship Resolved
Reference
is referenced by DDC-250 ArrayCollection Key Column @indexBy Resolved

 Description   

A Collection is like a php array, an ordered map. Hence there should be the possibility to persist this order.



 Comments   
Comment by Christian Heinrich [ 21/May/10 ]

Roman, I'd like to do this one as I have currently a use case for this. Do you have any idea of how to do this? What I'm wondering is whether it is possible to implement this without user intervention. (This would simply mean "store the entities as they were added"). But this would need another column in DB that we'd have to add within oneToMany / manyToMany relationships, but in this case one could save a serialized array holding "entityId => position" key / value pairs.

Afterwards, one could easily rebuild / reorder the collection via $collection->set($entity, $order[$entity->identifier]);

If you've got another thought about this, please don't hesitate to point me into the right direction!

Comment by Benjamin Eberlei [ 22/May/10 ]

this won't be implemented until 2.1, since its a pretty complex feature.

Changes are probably required in:

1. CollectionPersister - Add a new collection persister that takes the position into account
2. SchemaTool - Add a 'col_position' column to either the many-to-many or the one-to-many tables.
3. EntityPersister - Use and extend current order-by support to make the sorting happen

You can implement this already though with some performance hit in update scenarios. If you use the ORDER BY support and implement an API around your entity that abstracts those changes and always sets a "position" field on the many entity that is supposed to be sorted.

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

I don't think we necessarily need a new collection persister. Simply adjusting the ManyToManyPersister to be able to deal with it might be sufficient.

For OneToMany, that is always persisted from the "many" side, thus there is no collection persister, we would need to adjust the normal persisters.

They key element for the user should be a new annotation (or corresponding xml/yaml element) @OrderColumn. By default the order should not be persistent, only when an @OrderColumn annotation is present. The name of the order column can have a default, i.e. "position". Thus this enhancement of persisting the order should be fully backwards compatible.

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

On another note, the getInsertDiff/getDeleteDiff methods of PersistentCollection should already be "ready" for this. That is, when an element in the collection changed only its position, this is already tracked as a change. However the ManyToManyPersister issues no "UPDATE" queries, it simply deletes and inserts. A position change may be more effectively persisted with an UPDATE.

Comment by Benjamin Eberlei [ 30/Sep/10 ]

From a mailinglist entry, required check/changepoints:

1. ClassMetadata of Many-To-Many associations have to be extended to publish the required datastructure to the ORM.
2. All Metadata Mapping Drivers have to be extended
3. Persisters\ManyToManyCollectionPersister has to be extended to save the key in the many to many table if desired by the user.
4. Schema-Tool has to be extended to create the additional column.
5. PersistentCollection has to be extended so that lazy loading of collections with additional key works.
6. Array- and ObjectHydrator have to be extended to allow fetch join of collections with key column.
7. Discuss wheather to support this for One-To-Many also with the key-column on the many side. This is much more tricky internally though.

Comment by Benjamin Eberlei [ 24/Dec/10 ]

Push back to 2.x, we will have support for DDC-250 first and for this at a later release.

Comment by Thomas Tourlourat - Armetiz [ 07/Feb/12 ]

Hi there,
I'm looking for this feature.

Benjamin Eberlei said that : "You can implement this already", but I don't understand the "how to".

Also,
The problem should be solve if RDBMS had a "natural" order. An order based on item position inside table.

To get this feature without any change on Doctrine, I have remplace the PK defined by the target & mapped field identifier. The new PK is a new field with type "integer" and with auto-increment enable.
In this configuration, Doctrine use the "natural" order of the RDBMS. And I can change order of my item inside Collection and persist it.

It's an very bad solution, but It work before an official support.

Waiting for advices, and solutions,

Thomas.

Comment by Thomas Tourlourat - Armetiz [ 08/Feb/12 ]

Answering to Benjamin Eberlei on the "7. Discuss wheather to support this for One-To-Many also with the key-column on the many side. This is much more tricky internally though.".

I think that for One-To-Many relations, if user want to store the collection order, Doctrine can store the One-To-Many as Many-To-Many with a "model" limitation.
In that case, if storing order collection for Many-To-Many work, it should work for One-To-Many.

What do you think about it ?

Comment by Nicolas [ 29/Feb/12 ]

I think that it must be possible to have two keys ordering : the order isn't obligatory reversible.

For exemple with user and group :

  • You can order groups for one user : with preference by exemple, or importance.
  • And with a different order, users for a group : rank by example.

And maybe more, if you decide to add multi-order : an user show group by his rank in it, if his rank is identical, the order is make by love preference, and after by the importance given by the user (not necessary a number, if we imagine filter on them).

So a default order can be choice with parametized fields and could be :

 
@ManyToMany(targetEntity="Group")
...
@JoinFields ( rank: { type: int} , preference:{type:int}, importance:{type: string, length: 40} )
@OrderByJoinFields({"rank" = "ASC", "preference"="ASC", "importance"="ASC" } )

In this case the order must be optional and would be clean if another order appears in the same scope (DQL...). And manytomany became virtual entities act as other entities except they don't appears permetting in the same time a better conception.

So if the solution take in DDC-181 will become the only solution. This would a good idea to document this. Because, this seems to me a very important point.

My last point is even an unique ordering field created in the join table will be a big and usefull improvement.

Thank a lot for your beautiful work.

Comment by Thomas Tourlourat - Armetiz [ 29/Feb/12 ]

In my point of view, a collection can be order in a single way only.
If you want to add more than one order between User & Group, it's a new collection, a new relation.
Like :

  • User.memberOf() : Group[]
  • Group.members() : User[]
  • Group.importantMembers() : User[]

And it's your role to keep a consistency between members & importantMembers array.

Because ManyToMany join table is the reflection of a state of an ArrayCollection. It's not a usefull feature to be able to store all of the state of an ArrayCollection, even the order of this Array. It's just a normal feature that is really missing

Thomas.

Comment by Nicolas [ 29/Feb/12 ]

I don't think:

If you have three collection, you duplicate one relation 3 times and it's easy in consequence to lost the data integrity and unicity.

By example :

  • Thomas have rank 10 in Admin
  • Thomas think the admin group has importance noted 3 on all of his groups.
  • If a responsable of admin group decide to delete Thomas from it.
  • Thomas, in his ordered list of groups, think always to be in group admin.

So in my idea, the many to many relation isn't just an array collection, but should be an virtual entity. In UML or in Merise method this is a common problem to have a parametized relation. I think an orm should just implement this.

Comment by Thomas Tourlourat - Armetiz [ 29/Feb/12 ]

Hum,
I agree with you.. In a SQL Schema, it's a good choice to add many fields in a ManyToMany join table to description "order".

Comment by Thomas Tourlourat - Armetiz [ 07/Mar/12 ]

I just want to add a piece of Doctrine ORM Document :

"When working with collections, keep in mind that a Collection is essentially an ordered map (just like a PHP array). That is why the remove operation accepts an index/key. removeElement is a separate method that has O ( n) complexity using array_search, where n is the size of the map."

Comment by Thomas Tourlourat - Armetiz [ 23/Mar/12 ]

Hi there,
After several discussions. on IRC, I have changed my point of view.

Doctrine Documentation says : "When working with collections, keep in mind that a Collection is essentially an ordered map (just like a PHP array)".
So, I think that Doctrine have to be able to store or not the order of a Collection. By adding a new field on the Joined table to store the position of each elements.

But I not agree with @Nicolas. Because in his case, he's talking about Association Class : http://etutorials.org/Programming/UML/Chapter+6.+Class+Diagrams+Advanced+Concepts/Association+Class/
Because he's talking of a business logic, he's talking of a dedicated Entity class.

What do you think about it ?

Thomas;

Comment by Thomas Tourlourat - Armetiz [ 31/Aug/12 ]

Any news ?

Comment by Matthieu Napoli [ 16/Oct/12 ]

Hi, any news on this?

If I may add any info to this feature request, maybe something like JPA/Hibernate could be a good start?

See http://docs.oracle.com/javaee/6/api/javax/persistence/OrderColumn.html or http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/collections.html#collections-indexed

The idea in Hibernate is that you persist the order of the list in an extra column. This column is not a field of the entity however.

Comment by Albert Casademont [ 27/Jun/14 ]

+1, this would be indeed a very nice thing. We are using the @OrderBy annotation as a workaround but it's not quite the same thing

Comment by Marco Pivetta [ 27/Jun/14 ]

Moved to 3.x





[DDC-3195] indexBy implementation on containsKey of PersistentCollection in EXTRA LAZY mode uses property name as column name instead of column name Created: 26/May/14  Updated: 26/Jun/14

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

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

Any



 Description   

indexBy implementation on containsKey (and possibly other EXTRA LAZY implemented methods) of PersistentCollection in EXTRA LAZY mode uses property name as column name instead of column name for OneToMany collections

For example property = fieldName, column name field_name.
Set indexBy on OneToMany annotation to fieldName (as it should be ) and it tries to use fieldName in backend instead of field_name






[DDC-3189] blob doctrine2 not inserting file in mysql Created: 24/Jun/14  Updated: 26/Jun/14

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

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

Linux Ubuntu 12.04, Mysql 5


Attachments: PNG File a.png     Zip Archive testedoctrineupload.zip    

 Description   

I have an entity mapped as:

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

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

/** @Column(type="blob") **/
protected $arquivo;

When I use this (WORKS)

 $query = "INSERT INTO Upload1 (name, size, type, content ) "."VALUES ('$fileName', '$fileSize', '$fileType', '$content')";

 mysql_query($query)

When I use this doctrine way (NOT WORKING, if you try to get this file from mysql, return a corrupted or empty file)

$upload = new Upload();

$upload-> setContent($content);
$upload-> setName($fileName);
$upload-> setSize($fileSize);
$upload-> setType($fileType);

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

My html file:

<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr> 
<td width="246"> 
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile"> 
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload    "></td>
</tr>
</table>
</form>


 Comments   
Comment by Gustavo Monti Rocha [ 24/Jun/14 ]

trying to insert this image

Comment by Gustavo Monti Rocha [ 24/Jun/14 ]

Using:
$entityManager->getConnection()>getConfiguration()>setSQLLogger( new Doctrine\DBAL\Logging\EchoSQLLogger());

Getting:
"START TRANSACTION" INSERT INTO Upload (name, type, size, content) VALUES (?, ?, ?, ?) array(4) { [1] => string(5) "a.png" [2] => string(9) "image/png" [3] => int(264547) [4] => string(270342) "‰PNG  \0\0\0 IHDR\0\0@\0\0„\0\0\0v/jõ\0\0\0sBITÛáOà\0\0\0tEXtSoftware\0gnome-screenshotï¿>\0\0 \0IDATxœìw|TÅöÀÏܲ{·$›^I¥“Лҫ€ QPô©`

{êÏγ÷^ŸýYÀ‚ˆ\"¢ô %½m’í햙ߛ,›mÙe¾>š½÷Ι™3gæÎœ;]3ÿR P( …B¡P( …\0\0³X¾Ÿ†X]ŸÞ]ÿÂôP(\0àÜnñ¯N…B¡P( …B¡P(„B\0\0\\.÷ñ’ÊüünݺÇøîÚl¶m;æçfh4\0@BUR)”3®©šR( …B¡P( …ræa2Y+«ëV\0@4……}

Y–<¸§×KEÙ±ãHaaßâ¢#n·\0Ãf¦§ÄÇÇþÅé¦PÎ0¨‹B¡P( …B¡P(g(„ÙttTJ5\"\0< g§æefe¥ú?3rd¿Š £V.W7ì&\0˜âF+‰ø%9uÆF\0HINø«pôx…ZÅuÉL¥“Ô(‘Ù³¯\0ú÷í}ã¶9°A‡Óãr¥Åé¯n"... } array(4)

{ [1] => string(6) "string" [2] => string(6) "string" [3] => string(7) "integer" [4] => string(4) "blob" }

"COMMIT"

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

This looks more like a DBAL issue. Can you please provide the error/exception message that you receive from the driver/database server? Also do you use PDOMySQL or mysqli driver?

Comment by Gustavo Monti Rocha [ 26/Jun/14 ]

Steve,

I'm not getting any error/expection. Table looks like insert the blob file but when I try to download it is corrupted. You could see at getting .zip file and executing it.

I'm using PDOMysql.

Comment by Marco Pivetta [ 26/Jun/14 ]

This would probably need a data sample to reproduce the issue.

Comment by Gustavo Monti Rocha [ 26/Jun/14 ]

Marco,

you could use project attached and image in order to reproduce.

Comment by Marco Pivetta [ 26/Jun/14 ]

Gustavo Monti Rocha you should actually provide a functional test for this in case, see https://github.com/doctrine/dbal/tree/master/tests/Doctrine/Tests/DBAL

For example, the zip file you uploaded fails on various includes, and doesn't show the failures to me.





[DDC-274] Class and namespace naming inconsistency Created: 24/Jan/10  Updated: 26/Jun/14

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

Type: Improvement Priority: Major
Reporter: Glen Ainscow Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 1
Labels: None


 Description   

There are inconsistencies with some class and namespace names that include acronyms.

Examples:

Classes with upper-casing:
ORMException, DBALException, OCI8Connection, etc.

Classes with proper-casing:
RunDqlTask, CliException, MySqlPlatform, etc.

Namespaces with upper-casing:
DBAL, ORM, Doctrine\DBAL\Driver\PDOMsSql, etc.

Namespaces with proper-casing:
Doctrine\Common\Cli, Doctrine\DBAL\Tools\Cli\, Doctrine\ORM\Id, etc.

There is more proper-casing than upper-casing. IMHO, proper-casing is better as it's easier to read "SqlException" than it is to read "SQLException" (the "E" looks like part of the acronym), and things like "CLITask" can be avoided.

I discussed this a bit with Benjamin and Guilherme, and they were unsure and said that the whole team needed to reach consensus.

I'm leaving the priority as "Major" because this should probably be fixed sooner rather than later to prevent compatibility breaks.



 Comments   
Comment by Guilherme Blanco [ 25/Jan/10 ]

Increasing the severity and adding a fix version since this MUST be fixed before next release.

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

I find this to be of rather minor importance. You're talking of compatibility breaks, but thats only the case if we intend to start being very nitpicky about the naming in the future. We are currently not, and we wont be, so not much risk of later breakage.

We have a rule of thumb already: Acronyms up to 4 characters all uppercase, otherwise normal camelcase.

Now, it is often a matter of taste what is an acronym and what not and also not all acronyms have a clear casing, prime example mysql.

Being too nit-picky here is just a pain in the ass and we won't reach a common consensus anyway.

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

Oh and we better dont start arguing about whats better to read because there is no chance of agreement. If you ask me I find SQLException better than SqlException. So here we go. Lets better not run down this path.

Comment by Glen Ainscow [ 25/Jan/10 ]

No need to get upset, I'm only trying to help.

I just thought that consistency is usually a good idea, either way.

I have to disagree in that an acronym is an acronym, it's not a matter of taste, the letters either stand for something, or they don't.

As for "mysql", only the SQL part is an acronym. So, MySQL or MySql.

Close if you disagree.

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

I'm not upset. What made you think so? Maybe I should introduce a every now and then.

There's just no point in arguing about readability.

Like I said, we do have a naming standard even if its not adhered everywhere. The standard is also not something we've made up ourselves because we try to avoid that. When we introduced namespaces, we talked about adopting either the Java or .NET naming standards. We opted for the .NET standards. And there its recommended to write acronyms with up to 4 characters all uppercase.

I dont think there are too many violations of that in the code, probably Cli => CLI and some others but most of it looks ok to me.

UPDATE: Maybe we can gather a list here in this ticket of violations? Cli => CLI would be one. MySql => MySQL another. "Id" is rather an abbreviation of Identifier and not an acronym, to me at least.

Comment by Guilherme Blanco [ 25/Jan/10 ]

It's not a case of getting anyone upset...

But we should fix it and keep consistency of our codebase.

@romanb We should all talk and reach a common sense.
That's our last chance (last alpha) to get this consistency in.

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

@Guilherme: We do have a naming standard since a year. You want to change the standard now?

Comment by Glen Ainscow [ 25/Jan/10 ]

@Roman,

Just a feeling I got.

This issue was more about consistency (indicated in the title) than moving to proper-case naming.

I think it might be up to 3 characters in .NET, HtmlElement, System.Linq, etc. Anyway, not important.

I agree that Id. is an abbreviation.

There are some more violations. If you decide you want to change them, let me know and I'll compile a list.

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

@Glen: Yes, a list would be great. I find it hard to be 100% consistent sometimes though because my taste conflicts with the rule. For example, I would prefer "Id" over "ID", especially since it comes directly after ORM "Doctrine\ORM\ID\..." would be a bit too much. But I would not like "Orm" or "Dbal" either. But I think in most cases we can clearly fix the inconsistency. Like CLI or MySQL or MSSQL (or should it be MsSQL?).

Thanks for your help!

We should probably create updated coding standards for Doctrine 2 also, since they differ quite some from Doctrine 1 due to the introduction of namespaces and such. I'll create a ticket for that.

Comment by Glen Ainscow [ 25/Jan/10 ]

I'll do the list for you by tomorrow at the latest, just running out of time ATM.

Id is correct, as mentioned above, so that would be fine. MsSQL is correct (Ms = Microsoft = abbreviation).

Comment by Glen Ainscow [ 25/Jan/10 ]

Found some time ...

Doctrine\Common\Cache\ApcCache -> APCCache
Doctrine\Common\Cli -> CLI
Doctrine\Common\Cli\Printers\AnsiColorPrinter -> ANSIColorPrinter
Doctrine\Common\Cli\CliController -> CLIController
Doctrine\Common\Cli\CliException -> CLIException

Doctrine\DBAL\Driver\PDOMsSql -> PDOMsSQL
Doctrine\DBAL\Driver\PDOMySql -> PDOMySQL
Doctrine\DBAL\Driver\PDOPgSql -> PDOPgSQL
Doctrine\DBAL\Driver\PDOSqlite -> PDOSQLite
Doctrine\DBAL\Logging\EchoSqlLogger -> EchoSQLLogger
Doctrine\DBAL\Logging\SqlLogger -> SQLLogger
Doctrine\DBAL\Platforms\MsSqlPlatform -> MsSQLPlatform
Doctrine\DBAL\Platforms\MySqlPlatform -> MySQLPlatform
Doctrine\DBAL\Platforms\PostgreSqlPlatform -> PostgreSQLPlatform
Doctrine\DBAL\Platforms\SqlitePlatform -> SQLitePlatform
Doctrine\DBAL\Schema\Visitor\CreateSchemaSqlCollector -> CreateSchemaSQLCollector
Doctrine\DBAL\Schema\Visitor\DropSchemaSqlCollector -> DropSchemaSQLCollector
Doctrine\DBAL\Schema\MsSqlSchemaManager -> MsSQLSchemaManager
Doctrine\DBAL\Schema\MySqlSchemaManager -> MySQLSchemaManager
Doctrine\DBAL\Schema\PostgreSqlSchemaManager -> PostgreSQLSchemaManager
Doctrine\DBAL\Schema\SqliteSchemaManager -> SQLiteSchemaManager
Doctrine\DBAL\Tools\Cli -> CLI
Doctrine\DBAL\Tools\Cli\Tasks\RunSqlTask -> RunSQLTask

Doctrine\ORM\Mapping\Driver\PhpDriver -> PHPDriver
Doctrine\ORM\Mapping\Driver\XmlDriver -> XMLDriver
Doctrine\ORM\Mapping\Driver\YamlDriver -> YAMLDriver
Doctrine\ORM\Query\Exec\AbstractSqlExecutor -> AbstractSQLExecutor
(Should Doctrine\ORM\Query\Expr\Andx and Orx be AndX and OrX?)
Doctrine\ORM\Query\SqlWalker -> SQLWalker
Doctrine\ORM\Tools\Cli -> CLI
Doctrine\ORM\Tools\Cli\Tasks\RunDqlTask -> RunDQLTask
Doctrine\ORM\Tools\Export\Driver\PhpExporter -> PHPExporter
Doctrine\ORM\Tools\Export\Driver\XmlExporter -> XMLExporter
Doctrine\ORM\Tools\Export\Driver\YamlExporter -> YAMLExporter

... I think that's it. More than you expected? I did say: "There is more proper-casing than upper-casing."

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

No, not more than I expected. It's mostly SQL and CLI basically. Thanks for the list!

We should try to go through that list before beta.

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

Methods should be adjusted accordingly also (even though they're case insensitive). I already started with that. More to come.

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

Most of the Cli => CLI changes seem to be complete now.

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

Pushing the rest of the name changes towards beta2.

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

More renamings have been done but still more to do. Pushing remaining work to beta3.

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

Final name changes should be done prior to going into RC1.

Comment by Benjamin Eberlei [ 31/Oct/10 ]

there is much to be done yet, however most of it is also public API class names and might cause quite some BC breaks (i.e. DBAL Platforms and Schema Manager, Mapping Driver Names). I am not sure how to proceed here.

Comment by Roman S. Borschel [ 31/Oct/10 ]

Since PHP is mostly case-insensitive on class and method names it shouldn't be much of an issue.

Comment by Guilherme Blanco [ 16/Apr/14 ]

Scheduled to 3.0 as this may potentially create BC breaks





[DDC-2800] Something wrong with documentation generation Created: 18/Nov/13  Updated: 26/Jun/14

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

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


 Description   

The ArrayCollection has a matching() function, but it does not show in the API docs. http://www.doctrine-project.org/api/common/2.4/class-Doctrine.Common.Collections.ArrayCollection.html



 Comments   
Comment by Steve Müller [ 01/Apr/14 ]

Flip The collection API has moved to its own repo anyways now and there currently is no API generation for this, aswell as other subprojects like annotations etc. But the matching() method exists in 2.3 branch, where the repos were not separated, yet.

http://www.doctrine-project.org/api/common/2.3/source-class-Doctrine.Common.Collections.ArrayCollection.html#463-498

Do we need to keep this ticket open?

Comment by Flip [ 02/Apr/14 ]

I think so because no new documentation is generated for subprojects.

Expected: http://www.doctrine-project.org/api/collections/2.4/ (or any other latest version if the subprojects have seperate versioning)





[DDC-2693] Attribute/association overrides should be ignored when generating entities Created: 19/Sep/13  Updated: 26/Jun/14

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

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

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

 Description   

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

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

Generating entity "My\AppBundle\Entity\Job"

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

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


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

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

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

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





[DDC-3109] [Doctrine\ORM\Mapping\MappingException] Invalid field override named 'xxx' for class 'Entity\xxx' Created: 30/Apr/14  Updated: 26/Jun/14

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

Type: Bug Priority: Major
Reporter: david pichsenmeister Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: None
Environment:

kubuntu 14.04, php 5.5.9, MySQL 5.5


Attachments: File Organization.php     File User.php    
Issue Links:
Duplicate
duplicates DDC-2693 Attribute/association overrides shoul... Open

 Description   

Subclass should override association, but on generating entities, error:

[Doctrine\ORM\Mapping\MappingException]
Invalid field override named 'settings' for class 'Entity\Organization'.

is thrown. also, when updating schema, the assocations in the subclass are ignored (means are not present in the database).



 Comments   
Comment by Alexandre PAIXAO [ 23/May/14 ]

I think it is a duplicate of this bug : http://www.doctrine-project.org/jira/browse/DDC-2693





[DDC-3191] [GH-1072] Fix attempt of traversing bool in FileLockRegion Created: 26/Jun/14  Updated: 26/Jun/14

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

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


 Description   

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

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

Message:

Minor fix: on some platforms (i.e. ArchLinux) `glob()` returns `false` when nothing matched even though no errors occurred. As docs for `glob` say, such behavior is expected (see ‘Note’ at http://php.net/glob)

This made 1 existing test fail:

./vendor/bin/phpunit 
PHPUnit 4.3-g58f3a0e by Sebastian Bergmann.

Configuration read from /home/alex/git/doctrine2/phpunit.xml.dist

.............................................................   61 / 2495 (  2%)
........S.............E......................................  122 / 2495 (  4%)
.............................................................  183 / 2495 (  7%)
.............................................................  244 / 2495 (  9%)
.............................................................  305 / 2495 ( 12%)
.............................................................  366 / 2495 ( 14%)
.........................S...SSSS.S..........................  427 / 2495 ( 17%)
.............................................................  488 / 2495 ( 19%)
....................................................SS.......  549 / 2495 ( 22%)
.............................................................  610 / 2495 ( 24%)
.............................................................  671 / 2495 ( 26%)
.............................................................  732 / 2495 ( 29%)
.............................................................  793 / 2495 ( 31%)
.......................................................S.SSSS  854 / 2495 ( 34%)
SSSSSSSS.....................................................  915 / 2495 ( 36%)
.........................................SS..................  976 / 2495 ( 39%)
............S...S...........S..............................S. 1037 / 2495 ( 41%)
............................................................. 1098 / 2495 ( 44%)
..................S.......................................... 1159 / 2495 ( 46%)
.................................................SS.......... 1220 / 2495 ( 48%)
.......................S..................................... 1281 / 2495 ( 51%)
............................................................. 1342 / 2495 ( 53%)
............................................................. 1403 / 2495 ( 56%)
............................................................. 1464 / 2495 ( 58%)
............................................................. 1525 / 2495 ( 61%)
............................................................. 1586 / 2495 ( 63%)
.........S.................................................S. 1647 / 2495 ( 66%)
............................................................. 1708 / 2495 ( 68%)
............................................................. 1769 / 2495 ( 70%)
............................................................. 1830 / 2495 ( 73%)
............................................................. 1891 / 2495 ( 75%)
............................................................. 1952 / 2495 ( 78%)
............................................................. 2013 / 2495 ( 80%)
............................................................. 2074 / 2495 ( 83%)
............................................................. 2135 / 2495 ( 85%)
............................................................. 2196 / 2495 ( 88%)
............................................................. 2257 / 2495 ( 90%)
............................................................. 2318 / 2495 ( 92%)
............................................................S 2379 / 2495 ( 95%)
.......S......S.......S.....................S...........S.... 2440 / 2495 ( 97%)
.......................................................

Time: 14.37 seconds, Memory: 164.50Mb

There was 1 error:

1) Doctrine\Tests\ORM\Cache\FileLockRegionTest::testEvictAll
Invalid argument supplied for foreach()

/home/alex/git/doctrine2/lib/Doctrine/ORM/Cache/Region/FileLockRegion.php:204
/home/alex/git/doctrine2/tests/Doctrine/Tests/ORM/Cache/AbstractRegionTest.php:80

Traversing bool is no good and casting to array wouldn't hurt there as far as I can tell.






[DDC-3186] [GH-1069] added method to be able to reuse the console application Created: 24/Jun/14  Updated: 24/Jun/14

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

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


 Description   

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

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

Message:

This comes in handy, when you want to do more with the actual application object then just to run it.






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

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

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

Attachments: File DDC3184Test.php    

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

In master branch all works perfect

Comment by Dmitry Korotovsky [ 23/Jun/14 ]

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

Comment by Marco Pivetta [ 23/Jun/14 ]

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

Comment by Dmitry Korotovsky [ 23/Jun/14 ]

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

Comment by Marco Pivetta [ 23/Jun/14 ]

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





[DDC-3183] Add JsonSerializable to Collections Created: 22/Jun/14  Updated: 22/Jun/14

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

Type: New Feature Priority: Major
Reporter: Gabriel Bull Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: collection, orm


 Description   

Implement this:

http://www.php.net/manual/fr/class.jsonserializable.php

Can't really make this claim if Doctrine is not implementing basic interfaces for collections:

> The missing (SPL) Collection/Array/OrderedMap interface.






[DDC-3182] [GH-1066] Added jsonSerialize method to PersistentCollection Created: 22/Jun/14  Updated: 22/Jun/14

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

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


 Description   

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

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

Message:

Added jsonSerialize.

Here is to commit on collections:
https://github.com/doctrine/collections/pull/33



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

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





[DDC-3181] Class Table Inheritance - wrong table order on insert with more than one level of inheritance Created: 20/Jun/14  Updated: 20/Jun/14

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

Type: Bug Priority: Major
Reporter: M. de Lange Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: orm
Environment:

oracle



 Description   

note: this issue seems the same as DDC-732

When using class table inheritance with multiple levels i.e.:
Object -> SolidObject -> Building -> House
(House inherits from Building, Building from SolidObject, SolidObject from Object)

Object has the discriminator column and mapping. When persisting a new House entity I get a foreign key error because there is no row in the Building table.

I searched in the Code and found the problem. In the class "Doctrine\ORM\Persisters\JoinedSubclassPersister" in function "executeInserts()" around line 146 the array $subTableStmts is first declared and then filled with insert statements. The statement of the House-table is first added, and then the parent-tables (except the root-table "Object", since that one is executed first).

So the order in which the insert statements are executed is:
1 Insert into Object ...
2 Insert into House ... (which causes the error)
3 insert into Building ...
4 Insert into SolidObject

I edited the source to insert into the parent-tables (first SolidObject, then Building) before inserting into the table that belongs to the class that is persisted (House). And this works fine in my case.






[DDC-3055] table not escaped in orm:schema-tool:update if table already exists and needs to be altered Created: 27/Mar/14  Updated: 19/Jun/14

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

Type: Bug Priority: Major
Reporter: Hilz Simon Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

the schema tool had to alter a table which name needs to be escaped (and was properly configured to do so). this didnt work because the table name wasnt escaped. completely deleting the table in the db let the schema tool generate the correct querys with escaped table names.



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

Hilz Simon did you try this with master as well?

Comment by Jérôme Poskin [ 19/Jun/14 ]

Hi it seems to fail on version 2.4.3 too





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

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

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

Ubuntu 14.04, PHP 5.5.9-1ubuntu4, Symfony 2.5



 Description   

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






[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-3174] Query Cache not correct working when using SQLFilter Created: 17/Jun/14  Updated: 17/Jun/14

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

Type: Bug Priority: Major
Reporter: Benno Eggnauer Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: cache, sqlfilter


 Description   

We have an SQLFilter to filter on entities with a specific Trait implemented. The filter is very easy:

$res = $targetTableAlias . '.agency_id = ' . $this->getCurrentAgencyId();

On our system we have the query cache enabled, this works as long the "AgencyId" doesn't change. When the ID changes, the query cache seems to return the wrong (old cache) query.



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

I'm not sure if this case should be contemplated by the ORM. Filters are low-level and supposed to be stateless (services).

Comment by Benno Eggnauer [ 17/Jun/14 ]

OK, we can disable the query cache for this case. But then should at least the documentation be updated, which explicitly mentions to use filter for locales, which are also not stateless: http://doctrine-orm.readthedocs.org/en/latest/reference/filters.html#example-filter-class

Also in the query cache chapter: http://doctrine-orm.readthedocs.org/en/latest/reference/caching.html#query-cache

It is highly recommended that in a production environment you cache the transformation of a DQL query to its SQL counterpart. It doesn’t make sense to do this parsing multiple times as it doesn’t change unless you alter the DQL query.

Comment by Marco Pivetta [ 17/Jun/14 ]

Benno Eggnauer can you eventually provide a pull request?





[DDC-3170] SimpleObjectHydrator fails to get discriminator column from mapped SQL result Created: 17/Jun/14  Updated: 17/Jun/14

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

Type: Bug Priority: Major
Reporter: Ulf Reimers Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: hydrator, inheritance, orm


 Description   

When querying a simple entity which uses single table- or class table inheritance using simple object hydration (AbstractQuery::HYDRATE_SIMPLEOBJECT), the mapped discriminator column is not retrieved correctly.

Example:

/**
 * @Entity
 * @InheritanceType("JOINED")
 * @DiscriminatorColumn(name="type", type="string")
 * @DiscriminatorMap({"product" = "Product"})
 */
abstract class AbstractEntity
{
    /** @Id @Column(type="integer") @GeneratedValue */
    public $id;
}

/**
 * @Entity
 */
class Product extends AbstractEntity
{
}

$manager->createQueryBuilder()
                ->select('p')
                ->from('Product, 'p')
                ->getQuery()
                ->getResult(AbstractQuery::HYDRATE_SIMPLEOBJECT);

// -> Exception: [Doctrine\ORM\Internal\Hydration\HydrationException] The discriminator column "type" is missing for "Product" using the DQL alias "p".

The SQL statement used is equal to:

SELECT r0_.id AS id0, r0_.type AS type1 FROM Product r1_ INNER JOIN AbstractEntity r0_ ON r1_.id = r0_.id

As you can see, the type column is given an alias of type1. This is saved in the ResultSetMapping of the request but not taken into account when actually retrieving the discriminator column back from the SQL result.

The problem is inside SimpleObjectHydrator#hydrateRowData().

When the discriminator column name is fetched via

$discrColumnName = $this->_platform->getSQLResultCasing($this->class->discriminatorColumn['name']);

the result is simply type which is wrong because the alias is type2. This can be fixed by adding

if ($metaMappingDiscrColumnName = array_search($discrColumnName, $this->_rsm->metaMappings)) {
    $discrColumnName = $metaMappingDiscrColumnName;
}

right after the column retrieval, because then the alias of the meta field type is correctly taken into account.

I'll create a PR with a unit test for this fix right after this ticket's creation.

I hope I'm doing everything right, this is my first contribution.



 Comments   
Comment by Ulf Reimers [ 17/Jun/14 ]

PR is https://github.com/doctrine/doctrine2/pull/1060

I though that I first create a ticket, then propose a fix for that with a PR and by adding the Ticket ID in the PR-Title they are linked automatically. But unfortunately it seems I've done something wrong there.

Comment by Doctrine Bot [ 17/Jun/14 ]

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





[DDC-3171] [GH-1060] [DDC-3170] SimpleObjectHydrator fails to get discriminator column from mapped SQL result Created: 17/Jun/14  Updated: 17/Jun/14

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

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


 Description   

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

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

Message:

This PR fixes DDC-3170(http://www.doctrine-project.org/jira/browse/DDC-3170).

When querying a simple entity which uses single table- or class table inheritance using simple object hydration (``AbstractQuery::HYDRATE_SIMPLEOBJECT``), the mapped discriminator column was not retrieved correctly.

If the column got an alias during result set mapping other than it's actual name (e.g. ``type34`` instead of ``type``) than this alias wasn't correctly resolved when retrieving the discriminator column from the SQL result set.



 Comments   
Comment by Ulf Reimers [ 17/Jun/14 ]

I created DDC-3170 for this and put it into the PR like stated in https://github.com/doctrine/doctrine2/blob/master/CONTRIBUTING.md#doctrinebot-tickets-and-jira.

Unfortunately the BOT still created this issue here which can be removed in my opinion.

Comment by Doctrine Bot [ 17/Jun/14 ]

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





[DDC-3169] ManyToMany association fails when joining on a single column of a composity key Created: 17/Jun/14  Updated: 17/Jun/14

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

Type: Bug Priority: Major
Reporter: Bram Gerritsen Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: association, composite, orm


 Description   

I have two entities with a ManyToMany association between them. The first entity Campsite has a composite key (campsiteID, year). The second entity Region has a single key (regionID).
I want to create an association between Campsite::campsiteID and Region::regionID. See the entities below.

Campsite
/**
 * @ORM\Table(name="Campsite")
 */
class Campsite
{
    /**
     * @ORM\Id
     * @ORM\Column(name="campsiteID", type="integer", precision=0, nullable=false)
     */
    protected $campsiteID;

    /**
     * @ORM\Id
     * @ORM\Column(name="year", type="smallint", precision=0, nullable=false)
     */
    protected $year;

    /**
     * @ORM\ManyToMany(targetEntity="AcsiGeo\Entity\Region", fetch="EAGER", cascade={"detach"})
     * @ORM\JoinTable(name="CampsiteRegion",
     *   joinColumns={
     *     @ORM\JoinColumn(name="campsiteID", referencedColumnName="campsiteID", nullable=false)
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="regionID", referencedColumnName="regionID", nullable=false)
     *   }
     * )
     * @var \Doctrine\Common\Collections\ArrayCollection $regions
     */
    protected $regions;
}
Region
/**
 * @ORM\Table(name="Region")
 */
class Region
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     * @ORM\Column(name="regionID", type="integer", precision=0, nullable=false)
     */
    protected $regionID;
}

I run the following code to persist a new one.

$campsite = new Campsite();
$campsite->setCampsiteID(111111);
$campsite->setYear(2014);

$region = new Region();
$region->setRegionID(1);
$campsite->addRegion($region);

$em->persist($region);
$em->persist($campsite);
$em->flush();

This results in a record added to the CampsiteRegion table:

campsiteID : 2014
regionID: 1

This is clearly wrong as the value of the year field is added to the campsiteID column.

While debugging the problem I've found an issue with the method to determine the params in ManyToManyPersister on line 147.
The following code pops the last identifier from the array of identifiers.

$params[] = $isRelationToSource ? array_pop($identifier1) : array_pop($identifier2);

In my case:

array(
    'campsiteID' => 111111,
    'year' => 2014
)

Which picks 2014 as the value to use.
When I change the code to get the actual column from the array everything works as expected.

$params[] = $isRelationToSource ? $identifier1[$joinTableColumn] : $identifier2[$joinTableColumn];

I am not 100% sure if this change will have some side effects / edge case I'm not aware of.

For the time being I have fixed the problem bij just reversing the properties in my class, but this is not a real fix of course.






[DDC-1825] generate entities with traits Created: 18/May/12  Updated: 16/Jun/14

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

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

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



 Description   

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



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

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

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

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

        return $this;
    }

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

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

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

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

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

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

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

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

        return $this;
    }

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

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

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

}

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





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

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

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

Attachments: Text File undefined-joinColumn.patch    
Issue Links:
Duplicate
duplicates DDC-2808 Notice: Undefined index: joinColumns ... Resolved

 Description   

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

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

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



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

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

Comment by Litz Ouille [ 28/May/14 ]

Doctrine ORM 2.4.2 Here.

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

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

Comment by Marco Pivetta [ 30/May/14 ]

Calin Pristavu did you validate your mappings?

Comment by Calin Pristavu [ 30/May/14 ]

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

The many-to-one works just fine !

Comment by Litz Ouille [ 03/Jun/14 ]

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

Comment by Marco Pivetta [ 03/Jun/14 ]

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

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

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

Comment by Litz Ouille [ 03/Jun/14 ]

EDIT: Ok my bad.

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

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

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

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

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

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

multiple users can have multiple departments:

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

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

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

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

This results in this error:

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





[DDC-3165] one to zero or one with identity through foreign entity Created: 13/Jun/14  Updated: 13/Jun/14

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

Type: Bug Priority: Major
Reporter: Andries Seutens Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   
<?php

/**
 * @Entity
 */
class User
{
    /** 
     * @Id @Column(type="integer") 
     * @GeneratedValue 
     */
    private $id;
    
    /**
     * @ORM\OneToOne(targetEntity="Address")
     *
     * @var Address
     */
    private $address;
    
    public function getAddress()
    {
        return $this->address;
    }
}

/**
 * @Entity
 */
class Address
{
    /**
     * @Id @OneToOne(targetEntity="User") 
     */
    private $user;
    
    public function foo()
    {}
}


?>

The relation between user and address is one to zero or one. When a record exists on both sides, everything goes fine. When the right side (address) does not have a relevant record, calling $user->getAddress(); always returns an instance. Calling a method on that instance results in an exception:

Fatal error: Uncaught exception 'Doctrine\ORM\EntityNotFoundException' with message 'Entity of type 'Address' was not found.' in doctrine/orm/lib/Doctrine/ORM/Proxy/ProxyFactory.php on line 176

Expected behaviour:
$user->getAddress() should return NULL when the right side is empty.

NOTES:
Mind that the address is identified through a foreign entity (User)






[DDC-3161] [GH-1054] SQLFilters enahancements Created: 10/Jun/14  Updated: 10/Jun/14

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

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


 Description   

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

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

Message:

SQL filters in Doctrine are a bit too limited for my taste.
This pull request makes the current connection available inside sql filter classes.
The connection is needed to quote identifiers or values and generate sql statements for the current database. (sample use-case https://github.com/Atlantic18/DoctrineExtensions/blob/master/lib/Gedmo/SoftDeleteable/Filter/SoftDeleteableFilter.php)
Currently you can access the connection only through reflection which let's face it - is a hack.

I've also made the class depend on EntityManagerInterface instead of EntityManager.

There's a test for the new method.






[DDC-3159] CONCAT expression for PostGreSql Created: 10/Jun/14  Updated: 10/Jun/14

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

Type: Improvement Priority: Minor
Reporter: Maxime Colin Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: concat, dql, postgresql
Environment:

PostGreSQL



 Description   

For PostGreSQL, the CONCAT DQL function is translated in concatenation with || operator (which is the default behavior in AbstractPlatform class).

Is there a particular reason to not use the CONCAT PostGreSQL function instead like in MySqlPlatform ?

I ask this cause the concatenation with || operator return null if one of the part is null, whereas CONCAT function will simply ignore null values.






[DDC-3087] Entity code generation skip setters Created: 15/Apr/14  Updated: 07/Jun/14

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

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


 Description   

When executing `orm:generate-entities` to generated methods, do not generate setters when entity is readOnly `@ORM\Entity(readOnly=true)`



 Comments   
Comment by Christopher Stea [ 06/Jun/14 ]

I would like to see this feature but at the field level: Maybe my entity has a timestamp property that is auto-generated (uses Timestampable). I want to be able to have a getter but not a setter. Right now if I doctrine:generate and remove the setter function, it is re-created any time i re-run doctrine:generate.

I would suggest having @ORM/readonly as an available setting for properties.

Comment by Marco Pivetta [ 06/Jun/14 ]

I think this use case is simply a customization that should be applied by coding, and not via the generator.

Comment by Christopher Stea [ 07/Jun/14 ]

I have made the required edits and created a pull request:

https://github.com/doctrine/doctrine2/pull/1052
http://www.doctrine-project.org/jira/browse/DDC-3157

In the case of the original request, users can use readonly on every property in the table if they chose to make the entire entity read-only.

Comment by Doctrine Bot [ 07/Jun/14 ]

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

Comment by Marco Pivetta [ 07/Jun/14 ]

See comments on DDC-3157

Comment by Flip [ 07/Jun/14 ]

The PR by Christopher Stea adds a readonly annotation for properties. This ticket is about using the readonly annotation on the class (ORM\Entity) which is already in Doctrine. And just modify the code generator a little bit to skip the setters. Please reopen!!!

Comment by Marco Pivetta [ 07/Jun/14 ]

The PR introduces metadata used solely for the purpose of code generation.

Comment by Flip [ 07/Jun/14 ]

Yes that's not what THIS ticket is about, so please reopen because the PR is related, but not at all a solution to this ticket.

Comment by Marco Pivetta [ 07/Jun/14 ]

Hmm, makes sense. Re-opening then.





[DDC-3156] [GH-1050] DDC-3120 -- Catch ReflectionException for internal classes in ClassMetad... Created: 06/Jun/14  Updated: 06/Jun/14

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

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


 Description   

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

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

Message:

...ataInfo

I���m having an issue in relation to http://www.doctrine-project.org/jira/browse/DDC-3120 ��� When using ReflectionClass#newInstanceWithoutConstructor(); I���m getting a ReflectionException due to the class not being internal��� it���s resolveable by adding a try/catch to use ReflectionClass#newInstance. BUT, I���d like to know if there is something else going on here��� running PHP 5.5.13






[DDC-3155] orm:convert-mapping drops underscores from Doctrine type names specified in DB comments Created: 05/Jun/14  Updated: 05/Jun/14

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

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


 Description   

If you run orm:convert-mapping on a schema with comments like (DC2Type:json_array), the type name does get picked up, but the underscore is removed, so the type that ends up in the generated mapping's @Column annotation is jsonarray, not json_array.

The underscore being removed also seems to be affecting the EntityGenerator's attempt to map to correct PHP types for the @var annotation: that's showing up as just @var jsonarray even though the EntityGenerator should be mapping that to array. So it looks like the underscore is probably getting dropped at an earlier stage.






[DDC-3154] Conditions with Value Objects Created: 05/Jun/14  Updated: 05/Jun/14

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

Type: Improvement Priority: Minor
Reporter: Erik A. Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: value-objects


 Description   

I'm quite enthousiastic about Embeddables being added to Doctrine, but it's a pity that true Value Objects, which are compared by their properties, are not supported yet.

Given a Value Object Address with properties street and house number that you can instantiate with new Address("High Street", 1), and a User class that has an Address as Embeddable.

Then, the following is now supported:
DQL1:

SELECT u FROM User u WHERE (u.address.street = :street AND u.address.nr = :number)
    with { 'street' => 'High Street', 'number' => 1 }

Disadvantage: you should know the internal properties when writing your query. That's not how Value Objects usually are compared.

Instead, I expect to be able to do this:
DQL2:

SELECT u FROM User u WHERE (u.address = :address)
    with { 'address' => new Address("High Street", 1)  }

Internally, DQL2 could simply be transformed to the equivalent DQL1 by replacing the condition with conditions for each internal property. The advantage is that the one writing the query does not have to refer to the internal fields; the transformation is hidden.

A complicating factor is that Value Objects are Embeddables, but not every Embeddable is a Value Object. So there is always the question if objects need to be compared by reference or by their properties.

So, perhaps it's an idea to introduce a special operator ~ for comparing objects by their value to make the distinction explicit? Like so:
DQL3:

SELECT u FROM User u WHERE (u.address ~ :address)
    with { 'address' => new Address("High Street", 1)  }.

I created a pull request that contains an idea how the same concept (the ~ operator) might be applied to criterias on in-memory collections.

Just some thoughts and ideas. I'd love to hear some discussion on this as I think it would make Doctrine really powerful in supporting rich, expressive domain models. It would be great if both in-memory collections and DQL supported this!



 Comments   
Comment by Guilherme Blanco [ 05/Jun/14 ]

It should be the same operator, not a new one.
So this is the intended and desired behavior:

SELECT u FROM User u WHERE (u.address = :address)
    with { 'address' => new Address("High Street", 1)  }
Comment by Christophe Coevoet [ 05/Jun/14 ]

This would require to change the DQL to SQL conversion based on the fact that u.address is the path to an embeddable. It might impact performances
Using a separate operator would at least allow to know that it needs a special handling, without having to do complex changes to all places using the = operator.

A complicating factor is that Value Objects are Embeddables, but not every Embeddable is a Value Object. So there is always the question if objects need to be compared by reference or by their properties.

Embeddables cannot be compared by reference. They don't have an identity in the database. The only thing we have to compare them are their properties.

Comment by Erik A. [ 05/Jun/14 ]

True, if we look at the database level, we can only compare by reference. However, if you look beyond ORM and also to the Collections package, then if you want to do a matching on a collection of entities that have an Embeddable by using a Criteria on that Embeddable, then you do have both options (see my referenced pull request). Then two operators might come in handy, so that the additional operator can be introduced to both ORM as well as Collections.

If we would go for one operator (=), then I think the Criteria in Collection also needs to be changed so that it performs a loose comparison on objects and a strict comparison only on scalars. Perhaps that is already out of the scope of the current issue, but either way it would be preferrable to have a consistent solution.

Comment by Christophe Coevoet [ 05/Jun/14 ]

No, saying that we can only compare by reference is wrong. We *cannot* compare by reference (there is no way to reference them).

And talking about the needs of the criteria here is irrelevant, as this discussion is about building the DQL language, not about building the Criteria API. The criteria API can still have a separate operator to deal with value object even if the DQL uses = to compare embeddables. (btw, changing the Criteria comparison to loose on objects would break the comparison of relations, so it is totally impossible as it would be a BC break)

Comment by Guilherme Blanco [ 05/Jun/14 ]

Christophe Coevoet not a performance impact since DQL => SQL is cached.
Adding a new operator resolution requires bigger efforts and I'm pretty sure it'll be slower than converting u.address to multiple clauses (we do it already with composite identifiers).





[DDC-3149] [GH-1046] Fix the "Erroneous data format for unserializing" error message Created: 03/Jun/14  Updated: 03/Jun/14

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

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


 Description   

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

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

Message:

Backport patch from PR #1045 to 2.3 branch.

@ocramius - I'm not sure if this is viable, but based on the comments from people it could be helpful to have this fixed in 5.3? I'm not 100% sure whether PHP or Doctrine is at fault here?



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

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





[DDC-3148] ResultSetMappingBuilder::generateSelectClause ignores quoted column names Created: 02/Jun/14  Updated: 02/Jun/14

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

Type: Bug Priority: Major
Reporter: Christian Ruhstaller Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

If an entity has a quoted column (Magic Words etc.) and you want to use "generateSelectClause" for the specific entity it won't return the quoted name, just the plain name. If the name is a SQL Magic Word the corresponding SQL will fail.

Exp.: "profile.real" (wrong) instead of "profile.`real`".

File: Doctrine/ORM/Query/ResultSetMappingBuilder.php
Function: generateSelectClause

Line 445:
$sql .= " AS " . $columnName;

Example Entity:
...
class Profile

{ /** * @ORM\Column(name="`real`", type="boolean") */ protected $real=false; }




[DDC-2406] Merging of new detached entities with PrePersist lifecycle callback breaks Created: 19/Apr/13  Updated: 30/May/14

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

Type: Bug Priority: Major
Reporter: Oleg Namaka Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: merge,, prePersist


 Description   

Merging of new detached entities with PrePersist lifecycle callback breaks:

Code snippet:

    class A
    {
       /**
        *  @ORM\ManyToOne(targetEntity= ...
        *  @ORM\JoinColumn(name=" ...
        */
        protected $b;
        
        public function getB()
        {
            return $this->b;
        }
        
        public function setB($b)
        {
            $this->b = $b;
        }
        
        /**
         *
         * @ORM\PrePersist
         *
         * @return void
         */
        public function onPrePersist()
        {
           if ($this->getB() === null) {
                throw new \Exception('B instance must be defined);
           }
           ....
        }
    }
    
    class B 
    {
    }
    
    $a = new A();
    $b = $em->find('B', 1);
    $a->setB($b);
    $em->persist($a); // works fine as B instance is set
    $em->detach($a);
    
    $a = $em->merge($a) // breaks in onPrePersist

The reason it happens is that the merge operation is trying to persist a new entity created by uow::newInstance($class) without populating its properties first:

 // If there is no ID, it is actually NEW.
    ....
    if ( ! $id) {
        $managedCopy = $this->newInstance($class);

        $this->persistNew($class, $managedCopy);
    } else {
	....

This should happen first for the $managedCopy:

    // Merge state of $entity into existing (managed) entity
    foreach ($class->reflClass->getProperties() as $prop) {
        ....


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

Benjamin Eberlei, Is this an expected behavior ?

I mean.. This issue is about dispatch the event before copy the original values into the managed instance.
But overall, should $em->detach() trigger @PrePersist events ?

Comment by Benjamin Eberlei [ 01/May/13 ]

Fabio B. Silva he talks about $em->merge() on a detached entity calling pre persist. This should only happen on a NEW entity, not on a DETACHED one.

Comment by Oleg Namaka [ 01/May/13 ]

I tend to disagree with the statement above about pre persist that should not happen on a detached entity being merged back in. If this event handler contains a business logic that this entity needs to be checked against and the detached entity was modified before the merge operation in a way that invalidates it in the prePersist than I will end up with the invalid entity in the identity map. If the merge operation calls persist it must run the prePersist event handler as well for consistency.

If there is a logic that prevents persisting invalid entities why should it bypassed in the merge operation?

Comment by Cory Close [ 28/Nov/13 ]

I can confirm that this bug has not been fixed while using doctrine 2.4

Exactly as Oleg Namaka has described, my organization is trying to use @PrePersist callbacks to enforce validation on new entities.

However, we use an extensive client side framework that sends json back to our server. Our workflow is then:

deserializeJson into detached entity
merge detached entity to get it managed (this will apply our edits to an existing entity, or create a new one if this one is new)
persist

However, some entities run into the above problem while using this workflow, so our validation is not run. I can provide more code samples if required.

Comment by Oleg Namaka [ 29/Apr/14 ]

Whose feedback is it awaiting for?

Comment by Romaric Drigon [ 30/May/14 ]

I can confirm this issue.

My use case (which I guess is pretty standard):

  • I deserialize a new entity (with relationships to already existing ones)
  • I merge it to attach existing entities
  • I persist it

PrePersist is called on an entity with all properties set to null. Any modifications made inside this entity won't be saved to the DB.

Comment by Cory Close [ 30/May/14 ]

Is there any reason the proposed solution can't be implemented? I've patched a local version of Doctrine with the proposed changes and ran it through my application's tests without any issues, so I believe this would fix the problem.





[DDC-3147] [GH-1045] Fix the "Erroneous data format for unserializing" error message Created: 30/May/14  Updated: 30/May/14

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

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


 Description   

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

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

Message:

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



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

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





[DDC-3146] Hydrator memory leak when using iterator Created: 30/May/14  Updated: 30/May/14

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

Type: Bug Priority: Major
Reporter: Emiel Nijpels Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: hydrator, leak, memory
Environment:

PHP 5.4.21, OS X 10.9.3



 Description   

When the hydrator iterate() function is invoked, a new event is added to the event manager with a reference to the current hydrator object. This reference is never cleared which causes the hydrator object to never be cleared from memory by the PHP garbage collection.

/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php
$evm = $this->_em->getEventManager();
$evm->addEventListener(array(Events::onClear), $this);

The effects of this bug are best visible when creating multiple iterator objects after each other in a repository:

// Loop through test code 10 times
for ($f = 0; $f < 10; $f++) {
    // Create test query
    $query = $this->createQueryBuilder('p')->getQuery();

    // Create IterableResult object
    $iterableResult = $query->iterate();

    // Loop through the iterator
    foreach ($iterableResult as $row) {}

    // Print out memory usage
    print(memory_get_usage() . PHP_EOL);
}

This results in the following output:

10536552
10549920
10563288
10576664
10590040
10603416
10616792
10630168
10643608
10656984

Notice how the used memory increases by about 13KB after each iteration.
To stop this memory leak the following code can be added to the end of the cleanup() function in the AbstractHydrator class:

$evm = $this->_em->getEventManager();
$evm->removeEventListener(array(Events::onClear), $this);

The output is now:

10537920
10537048
10537048
10537048
10537048
10537048
10537048
10537048
10537048
10537048

The reference to the event manager is now automatically removed in the cleanup function which allows the hydrator object to be cleaned up by the garbage collection function in PHP.






[DDC-3136] DQL JOIN association return null Created: 24/May/14  Updated: 24/May/14

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

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

Symfony2



 Description   

Hello,
I observe a strange behavior of a query result done by DQL (only tested DQL in fact). In the last entry of my result, the joined entity are returned to null

My tables are:

Entity1
/**
 * @ORM\Table(name="entity1")
 * @ORM\Entity()
**/
class Entity1
{	
	 /**
     * @ORM\Column(name="entity1_id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
	protected $entity1_Id; 
	
	/**
	* @ORM\Column(name="entity1_text", type="string")
	*/
    protected $entity1_Text;
}
Entity2
/**
 * @ORM\Table(name="entity2")
 * @ORM\Entity()
**/
class Entity2
{	
        /**
	* @ORM\OneToOne(targetEntity="Entity1")
	* @ORM\JoinColumn(name="entity1_id", referencedColumnName="entity1_id")
	* @ORM\Id
	*/
	protected $entity1_id; 
    
	/**
	* @ORM\ManyToOne(targetEntity="Entity3")
	* @ORM\JoinColumn(name="entity3_id", referencedColumnName="entity3_id")
	*/
	protected $entity3; 
}
Entity3
/**
 * @ORM\Table(name="entity3")
 * @ORM\Entity()
**/
class Entity3
{	
	 /**
     * @ORM\Column(name="entity3_id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
	protected $entity3_Id; 
	
	/**
	* @ORM\Column(name="entity3_text", type="string")
	*/
    protected $entity3_Text;
}

So when I do a simple request like this:

DQL Request
SELECT ent2, ent3 FROM f4cIndexBundle:Entity2 ent2 JOIN ent2.entity3 ent3

The result is looks like this

Result NOK
array (size=2)
  0 => 
    object(f4c\IndexBundle\Entity\Entity2)[550]
      protected 'entity1_id' => 
        object(Proxies\__CG__\f4c\IndexBundle\Entity\Entity1)[502]
          ...
      protected 'entity3' => 
        object(f4c\IndexBundle\Entity\Entity3)[497]
          protected 'entity3_Id' => int 2
          protected 'entity3_Text' => string 'TEXT OF ENTITY 3 - SPECIFIC 2' (length=29)
  1 => 
    object(f4c\IndexBundle\Entity\Entity2)[498]
      protected 'entity1_id' => 
        object(Proxies\__CG__\f4c\IndexBundle\Entity\Entity1)[499]
          ...
     protected 'entity3' => null

The entity3 of the last result is never joined and set to null (it's not possible because of the JOIN no ?)
I spent to days on this and I observed that when I add a property in my entity 2 like this

Entity2
/**
 * @ORM\Table(name="entity2")
 * @ORM\Entity()
**/
class Entity2
{	
    ...
    /**
	* @ORM\Column(name="entity2_text", type="string")
	*/
    protected $entity2_Text;
}

The result is ok

Result OK
array (size=2)
  0 => 
    object(f4c\IndexBundle\Entity\Entity2)[550]
      protected 'entity1_id' => 
        object(Proxies\__CG__\f4c\IndexBundle\Entity\Entity1)[498]
         ...
      protected 'entity2_Text' => string 'TEXT2' (length=5)
      protected 'entity3' => 
        object(f4c\IndexBundle\Entity\Entity3)[499]
          protected 'entity3_Id' => int 1
          protected 'entity3_Text' => string 'TEXT OF ENTITY 3 - SPECIFIC 1' (length=29)
  1 => 
    object(f4c\IndexBundle\Entity\Entity2)[494]
      protected 'entity1_id' => 
        object(Proxies\__CG__\f4c\IndexBundle\Entity\Entity1)[495]
          ...
      protected 'entity2_Text' => string 'TEXT1' (length=5)
      protected 'entity3' => 
        object(f4c\IndexBundle\Entity\Entity3)[496]
          protected 'entity3_Id' => int 2
          protected 'entity3_Text' => string 'TEXT OF ENTITY 3 - SPECIFIC 2' (length=29)

Is it normal ? Is this a kwon issue ?

Thanks for your help

Raphael P.






[DDC-3135] Unnecessary SELECT after updating of versioned table Created: 23/May/14  Updated: 23/May/14

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

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

PHP 5.5.9-1ubuntu4 (cli) (built: Apr 9 2014 17:11:57)



 Description   

When I update entity with version doctrine generates 2 SQLs:

INSERT INTO TableA (key, value) VALUES (1, 1);
SELECT version FROM TableA WHERE key = 1;

OR

UPDATE TableA SET value= 2, version = version + 1 WHERE key = 1 AND version = 1;
SELECT version FROM TableA WHERE key = 1;

Not only second query is unnecessary (version value is always 1 after persisting and is always prev version + 1 after successful update) but can also read incorrect value if row is updated between update and select statement. In this case entity manager will have outdated data, but most recent version.






[DDC-3134] Inconsistent defaults for onDelete when defining many-to-many relations Created: 23/May/14  Updated: 23/May/14

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

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

Symfony 2.5.0-BETA2



 Description   

When defining a relation with the following annotation:

/**
 * @ORM\ManyToMany(targetEntity="A\B\C")
 */

The following SQL is generated for the foreign key constraints:

ALTER TABLE the_table ADD CONSTRAINT FK_A63A409AA76ED395 FOREIGN KEY (something1) REFERENCES thing2 (id) ON DELETE CASCADE;
ALTER TABLE the_table ADD CONSTRAINT FK_A63A409AF8BD700D FOREIGN KEY (something2) REFERENCES thing1 (id) ON DELETE CASCADE;

As it can be seen, the default seems to be to include ON DELETE CASCADE. This feels like a dangerous behaviour (and I couldn't find it documented), but fair enough. The inconsistency comes when adding:

/**
 * @ORM\ManyToMany(targetEntity="A\B\C")
 * @ORM\JoinTable(name="the_table",
 *      joinColumns={@ORM\JoinColumn()},
 *      inverseJoinColumns={@ORM\JoinColumn()}
 * )
 */

In this case, even if we are not providing any values for the join and inverse join columns, we get:

ALTER TABLE the_table ADD CONSTRAINT FK_A63A409AA76ED395 FOREIGN KEY (something1) REFERENCES something2 (id);
ALTER TABLE user_unit ADD CONSTRAINT FK_A63A409AF8BD700D FOREIGN KEY (something2) REFERENCES something1 (id);

As it can be seen, the ON DELETE CASCADE is gone.

I understand this is the case because, when giving empty JoinColumn annotations it's not the engine defaults that are processed, but the inferred values for the annotation. Still, this seems to be either a bug or an undocumented behaviour.

Am I doing anything wrong here? Should this be looked into?






[DDC-3016] Criterias do not work with embeddables when matching in memory Created: 07/Mar/14  Updated: 22/May/14

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

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


 Description   

When using criterias and doing the matching on a collection already loaded in memory, it will not work if filtering on embeddable objects.

Example:

    $criteria = new Criteria();
    $criteria->andWhere($criteria->expr()->eq('actions.view', true));

    $authorizations = $this->authorizations->matching($criteria);

Here the ClosureExpressionVisitor will try to get the property named >actions.view instead of >actions->view.

PHPUnit_Framework_Error_Notice : Undefined property: Tests\...\Model\ArticleAuthorization::$actions.view


 Comments   
Comment by Matthieu Napoli [ 22/May/14 ]

I have opened a PR with a potential fix: https://github.com/doctrine/collections/pull/27





[DDC-3104] Invalid count on EXTRA LAZY collection of SINGLE TABLE entities Created: 28/Apr/14  Updated: 20/May/14

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

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

Issue Links:
Reference
relates to DDC-1595 Wrong count in relation with inheritance Resolved

 Description   
  • This issue relates to http://www.doctrine-project.org/jira/browse/DDC-1595
  • With the following entities
    • EntityPromotionAbstract entity:
      * @ORM\Entity
       * @ORM\InheritanceType("SINGLE_TABLE")
       * @ORM\Table(name="entity_promotion")
       * @ORM\DiscriminatorColumn(name="type", type="string")
       * @ORM\DiscriminatorMap({
       *     "brand"           = "BrandPromotion",
       *     "category"        = "CategoryPromotion",
       * })
       */
      abstract class EntityPromotionAbstract
      
    • CategoryPromotion entity:
       * @ORM\Entity
       */
      class CategoryPromotion extends EntityPromotionAbstract
      {
          /**
           * Category
           *
           * @var Category
           * @ORM\ManyToOne(targetEntity="Category", inversedBy="CategoryPromotions")
           * @ORM\JoinColumn(name="instance_id", referencedColumnName="category_id")
           */
          protected $Category;
      ...
      }
      
    • BrandPromotion entity:
       * @ORM\Entity
       */
      class BrandPromotion extends EntityPromotionAbstract
      {
          /**
           * Brand
           *
           * @var Brand
           * @ORM\ManyToOne(targetEntity="Brand", inversedBy="BrandPromotions")
           * @ORM\JoinColumn(name="instance_id", referencedColumnName="brand_id")
           */
          protected $Brand;
      }
      
    • Brand entity:
          /**
           * Associated BrandPromotions
           *
           * @var \Doctrine\Common\Collections\Collection
           *
           * @ORM\OneToMany(targetEntity="BrandPromotion", mappedBy="Brand", fetch="EXTRA_LAZY")
           */
          protected $BrandPromotions;
      
    • Category entity:
          /**
           * Associated CategoryPromotions
           *
           * @var \Doctrine\Common\Collections\ArrayCollection|\Doctrine\ORM\PersistentCollection
           *
           * @ORM\OneToMany(targetEntity="CategoryPromotion", mappedBy="Category", fetch="EXTRA_LAZY")
           */
          protected $CategoryPromotions;
      
  • When Brand::BrandPromotions collection is not initialized, calling count on it will return a count of BrandPromotion and CategoryPromotion elements, but calling isEmpty will return a count of BrandPromotion entities only.
  • \Doctrine\ORM\Persisters\OneToManyPersister::count does not take into account a discriminator value of 'brand':
            foreach ($targetClass->associationMappings[$mapping['mappedBy']]['joinColumns'] as $joinColumn) {
                $whereClauses[] = $joinColumn['name'] . ' = ?';
    
                $params[] = ($targetClass->containsForeignIdentifier)
                    ? $id[$sourceClass->getFieldForColumn($joinColumn['referencedColumnName'])]
                    : $id[$sourceClass->fieldNames[$joinColumn['referencedColumnName']]];
            }
    
    
  • This results in a query:
    SELECT count(*) FROM entity_promotion t WHERE instance_id = ?
    
  • The query should include a type condition:
    SELECT count(*) FROM entity_promotion t WHERE instance_id = ? AND (t.type in 'brand')
    


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

Why would the query include a type conditional? To me, it seems like the association was built between invalid data types instead.

Comment by Oleg Namaka [ 06/May/14 ]
  • Could you elaborate on what exactly you mean when you are saying, that the association was built between invalid data types?
  • Even if your statement is valid, then why calling on a initialized collection $collection->isEmpty() produces a correct result? Calling $collection->count() produces also a correct result on an initialized collection, wheres calling $collection->count() on an unitialized collection results in an invalid element count.
Comment by Marco Pivetta [ 06/May/14 ]

Ah, I see what you mean now. Sorry, I was confusing this with a joined table inheritance.

Comment by Vigintas Labakojis [ 20/May/14 ]

Exactly same behaviour just wasted me a few hours. Shame I'll have to switch fetch mode back to LAZY until this gets fixed.





[DDC-547] Consider allowing custom PersistentCollection implementations Created: 27/Apr/10  Updated: 20/May/14

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

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


 Description   

We should consider allowing the configuration of custom PersistentCollection implementations on a per-association basis.
This could allow users to craft optimized (SQL) behavior for for some of their collections to improve performance without changing the domain model code.

For this, PersistentCollection needs to be designed for inheritance.



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

Rescheduled for 2.1. Might be 2.x.

Comment by Benjamin Eberlei [ 24/Dec/10 ]

Reschedule for 2.x

Comment by Wouter Wiltenburg [ 20/May/14 ]

Any progress on this new feature?

Comment by Marco Pivetta [ 20/May/14 ]

This can't be solved in the 2.x series because of the tight coupling between association UnitOfWork logic and the PersistentCollection API.





[DDC-1739] [GH-314] [WIP] Doctrine\Common metadata drivers reuse Created: 30/Mar/12  Updated: 19/May/14

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

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


 Description   

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

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

Message:

This PR is strictly related with https://github.com/doctrine/common/pull/98 and tests won't pass until the doctrine-common submodule points to a merged version of it (will do so later, so please don't merge now ).

Basically, I just stripped any code duplicate of what already available in dcom master under Doctrine\Common\Persistence\Mapping\Driver.

Tests are OK on my environment when using the new commons submodule.

(This is a cleanup for #263, where I sadly did pull from the remote branch after rebasing)

Tests are still failing.



 Comments   
Comment by Benjamin Eberlei [ 30/Mar/12 ]

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

Comment by Benjamin Eberlei [ 30/Mar/12 ]

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

Comment by Benjamin Eberlei [ 30/Mar/12 ]

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

Comment by Benjamin Eberlei [ 30/Mar/12 ]

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

Comment by Benjamin Eberlei [ 01/Apr/12 ]

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

Comment by Benjamin Eberlei [ 04/Apr/12 ]

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

Comment by Benjamin Eberlei [ 06/Apr/12 ]

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

Comment by Benjamin Eberlei [ 07/Apr/12 ]

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

Comment by Doctrine Bot [ 19/May/14 ]

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





[DDC-3130] [GH-1033] [WIP] Lazy criteria for ManyToMany collection Created: 18/May/14  Updated: 18/May/14

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

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


 Description   

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

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

Message:

This continues my previous work on making Criteria most efficient.

Currently we are wrapping matching calls on repositories and matching calls on EXTRA_LAZY associations around a LazyCriteria. However, ManyToMany are still completely loaded: https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/PersistentCollection.php#L874

This is still problematic from a performance point of view because count, contains... cannot be optimized. I think the solution is similar to previous one, hence creating a Lazy collection for that kind of associations.

However, this is really tricky to do because of the whole mess inside the persisters (can't wait for them to be completely refactored, it's getting really hard to maintain this mess ).






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

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

Type: Improvement Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: mapping, postgresql, sqlite

Issue Links:
Dependency
depends on DBAL-900 [GH-600] Support for Partial Indexes ... Open

 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





[DDC-3122] Querying entities with ResolveTargetEntity Created: 14/May/14  Updated: 15/May/14

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

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


 Description   

Hello

The problem refers to a following situation:
You have 2 classes that use a quite simple inheritance and an interface:

interface CInterface { /* ... */ }
class AClass implements CInterface { /* ... */ }
class BClass extends class AClass { /* ... */ }

When we configure the ResolveTargetEntityListener the following way:

array(
  'CInterface' => 'BClass'
)

when using the entity manager to find an entity:

$entityManager->find('BClass', $id);

we'll get a following Doctrine\DBAL\DBALException:

An exception occurred while executing 'SELECT t1.id AS id2 FROM bclass_table_name t1 WHERE t0.id = ?' with params [1]:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 't0.id' in 'where clause'

As you can see the column names are generated properly but the WHERE clause has an invalid refference to t0 table (should be t1).

Similar problem:

http://stackoverflow.com/questions/17588682/doctrine-inheritance-replacement



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

Is AClass a mapped superclass or the root of the inheritance?

Comment by Heo [ 15/May/14 ]

AClass is the root of the inheritance. I would like to add that the only problem is the "find" method. Database relations are created properly (with the SchemaTool), all keys refer to proper columns.

Comment by Marco Pivetta [ 15/May/14 ]

Heo can you abstract a test case for this?





[DDC-2339] [GH-605] DDC-2338 Added failing test for composite foreign key persistance Created: 07/Mar/13  Updated: 13/May/14

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

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


 Description   

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

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

Message:

I've added this test regarding ticket DDC-2338



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

This is documented behavior and would just be an improvement

Comment by Doctrine Bot [ 13/May/14 ]

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





[DDC-3063] Unexpected behavior with 'WHERE NOT IN' and empty array Created: 01/Apr/14  Updated: 06/May/14

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

Type: Bug Priority: Major
Reporter: Tim Stamp Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: None
Environment:

CentOS, PHP 5.4, mysql



 Description   

I tried to set version to 2.4.0 but was prevented.

Assume the set 'n' contains 10 records, all with id > 0.

->andWhere('n.id NOT IN (:ids)')->setParameter('ids', [])
returns 0 records.

->andWhere('n.id NOT IN (:ids)')->setParameter('ids', [0])
returns 10 records.


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

This is a simple misunderstanding of how SQL IN() works

Comment by Tim Stamp [ 01/Apr/14 ]

You're right that its invalid SQL, but this is DQL. In SQL this would raise an error, in DQL it says nothing and returns nothing.

Isnt there a way to check if a statement has caused this error?

Comment by Marco Pivetta [ 01/Apr/14 ]

Tim Stamp yeah, when using IN() and NOT IN() you should actually check if the parameters are empty or not before adding the clause.

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

It's still weird that no error is raised by that. Tim Stamp can you check what SQL is generated by your query?

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

Hehe I think I got the problem. It might be DBAL related. See:

https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/SQLParserUtils.php#L140
https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/SQLParserUtils.php#L169

Looks like the implementing person did that by intention but don't ask me why.

Comment by Marco Pivetta [ 01/Apr/14 ]

Thats to avoid having an SQL statement like

SELECT * FROM foo WHERE bar IN()

, which is invalid.

Indeed, the NOT IN() case is not contemplated by that.

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

Just wondering if that kind of implementation isn't changing expectations because it looks like IN(NULL) will select all NULL rows then, even though this is not explicitly requested by the user. I don't care really TBH but this behaviour is not very transparent to the user. Personally I would like to see an error instead... Then at least I know what's going on and can fix that by additional checks instead.

Comment by Marco Pivetta [ 01/Apr/14 ]

Makes sense. Re-opening.

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

The question is if we can change this behaviour without breaking applications that rely on the current one. Because changing the code to throw an error breaks applications that insist on returning 0 rows for an empty array. I don't know what rules apply here concerning BC. What do you think Marco Pivetta?

Comment by Marco Pivetta [ 01/Apr/14 ]

Steve Müller existing apps should do following anyway:

if ($productIds) {
    $qb->andWhere('p.id IN (:productIds)')->setParameter('productIds', $productIds);
}

If they are not, that's most likely a bug in their codebase.

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

Agree. Was just wondering about what we can expect and what we can't expect.

Comment by Guilherme Blanco [ 21/Apr/14 ]

Steve Müller feel free to patch DBAL.
It's a bug, not a supported feature. If we have 2 tickets:
1- If I pass an empty array, I get nullable rows and I can't fix this
2- If I pass an empty array, it used to return nullable rows, now it returns nothing
Which one would you fix?

Comment by Tim Stamp [ 06/May/14 ]

Guilherme Blanco shouldn't both these use cases throw an exception, as both cases in MySQL would return an error?





[DDC-3115] UnitOfWok can't access proxies protected property Created: 04/May/14  Updated: 04/May/14

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

Type: Bug Priority: Major
Reporter: Machete Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: orm
Environment:

php5.5.11-1~dotdeb.1
debian 7.5 64bit
apache2
doctrine-orm-module 0.8.0


Attachments: PNG File doctrine-error.PNG    

 Description   

Running the code on different environments for a while now, I have never had any problems. Recently I installed the code onto a different server and I've been experiencing the following issue:

> Fatal error: Cannot access protected property DoctrineORMModule\Proxy_CG_\Page\Entity\PageRevision::$date in src/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 2596

I am absolutely clueless, why this happens. It seems to be affecting only specific data rows, as you might reproduce here: http://de.serlo.org/pages

The field is defined as followed:

    /**
     * @ORM\Column(type="datetime", options={"default"="CURRENT_TIMESTAMP"})
     */
    protected $date;

However, the exact same database snapshot works fine here: http://ptr.serlo.org/pages

Attached you will find a screenshot of the datarows. The yellow ones mark each one working and one not working row.

I have no idea what the problem is here.



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

Discussed this on IRC - very tricky, seems like one of the servers has the reflection property not set to "accessible"

Comment by Machete [ 04/May/14 ]

Adding `$class->reflFields[$field]->setAccessible(true)` before line 2596 resolved this issue. Even after removing it, everything worked fine.

note to self:
> [18:23] <@ocramius> machete_: can you find out where that particular property is instantiated?
> [18:23] <@ocramius> should be in `ClassMetadataInfo::wakeUpReflection()` or such
> [18:25] <@ocramius> if you find that again, consider looking at locations in the code where `new ReflectionClass()` is instantiated





[DDC-3113] Associated entity with "cascade" persist that is eagerly loaded doesn't get saved when its parent is flushed Created: 01/May/14  Updated: 01/May/14

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

Type: Bug Priority: Major
Reporter: Juraj Seffer Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Address entity definition within User class
/**

  • Address
    *
  • @ORM\OneToOne(targetEntity="Address", fetch="EAGER", cascade="persist")
  • @var \Application\Entity\Address
    */
    protected $address;

When User gets loaded via Doctrine, the resulting Address object within the User is not a proxy object but the concrete class specified in targetEntity. When trying to persist the User:

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

User object gets saved and another associated entity that is lazy loaded does get saved. What doesn't get saved into the database is the Address object. No exceptions are thrown, the Address object is simply ignored.






[DDC-3112] Class Table Inheritance Created: 01/May/14  Updated: 01/May/14

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

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

mysql-5.6.13-winx64, SQL Server 2012, PHP-5.5.4, Windows 7 64 bits professional



 Description   

The documentation on Class Table Inheritance could use some improvements.

1. It's not very clear which classes can have an IDENTITY (auto increment). Consider the example parent: Person, child: Employee. Then add another child: Employer. (this scenario assumes of course that an Employer can never be an Employee). When entering 4 Persons the information in the tables could look like this:
`Parent: (1, Employee), (2, Employee), (3, Employer), (4, Employee) Child Employee: 1,2,4 Child: Employer: 3`
So that means a child can not have an IDENTITY.

Suggestion: specify in docs parent can have IDENTITY, children must not have IDENTITY

2. The parent MUST have an "identifier/primary key" (notice that identifier is not the same as IDENTITY/auto increment). This is not shown in the docs and will throw this:
`Fatal error: Uncaught exception 'Doctrine\ORM\Mapping\MappingException' with message 'No identifier/primary key specified for Entity "MyProject\Model\Person". Every Entity must have an identifier/primary key.'`

Suggestion: specify parent must have identifier/primary key, children primary key will be taken from parent class and must not be specified again in child entity.

3. Is it possible to let a child have it's own identity? And reference the child in the parent table not but the parent's primary key but by a Foreign Key. This blog post here http://blog.liip.ch/archive/2012/03/27/table-inheritance-with-doctrine.html leads me to belief this was once the case (because parent has id and related_id) but perhaps was taken out in later doctrine versions?

Suggestion: specify pros and cons from implementation with FK and without FK (and/or why this changed in history)

4. Show Generated SQL to help understanding. For MySQL:
CREATE TABLE Person (id INT NOT NULL, discr VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB
CREATE TABLE Employee (id INT NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB
ALTER TABLE Employee ADD CONSTRAINT FK_A4E917F7BF396750 FOREIGN KEY (id) REFERENCES Person (id) ON DELETE CASCADE

For SQL Server:
CREATE TABLE Person (id INT NOT NULL, discr NVARCHAR(255) NOT NULL, PRIMARY KEY (id))
CREATE TABLE Employee (id INT NOT NULL, PRIMARY KEY (id))
ALTER TABLE Employee ADD CONSTRAINT FK_A4E917F7BF396750 FOREIGN KEY (id) REFERENCES Person (id) ON DELETE CASCADE

5. Since the parent forces the identity of the child (through a constraint), a child can not manage it's own identity. Which is important to know if you want to merge already existing data. With the constraint on the primary key the database follows very closely the conceptual model in the PHP classes, but looses flexibility on the database schema implementation level. While this could be resolved with a Foreign Key where then you loose strictness of the database and the responsibility shifts back to the application.






[DDC-3110] paginator doesn't respect order by clause when using the fetchJoinCollection flag Created: 30/Apr/14  Updated: 30/Apr/14

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

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

MariaDB 5.5



 Description   

I have a DQL query with a ORDER BY clause.
When I paginate the result with new Paginator($query, $fetchJoinCollection = true); the orderind isn't correct.
The order is lost in the second request (Perform a Limit Subquery with DISTINCT to find all ids of the entity in from on the current page)

It creates a SQL query like that :
SELECT
DISTINCT id0
FROM
(
SELECT
d0_.id AS id0,
d0_.name AS name1,
d0_.note AS note2,
FROM
data d0_
ORDER BY
d0_.note DESC
) dctrn_result
LIMIT
20 OFFSET 0

The external SELECT don't keep the order so it just fetch the 20 first elements from the whole table.






[DDC-3108] Criteria cannot reference a joined tables' fields when used with an ORM QueryBuilder Created: 30/Apr/14  Updated: 30/Apr/14

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

Type: Bug Priority: Major
Reporter: Chris Rog Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: criteria, dql, orm, querybuilder


 Description   

This regression was introduced in 2.4.2 with the addition of the "rootAlias" stuff. Basically, the hard-coded addition of the rootAlias + "." prevents any Criteria object from referencing any field that isn't on the first table selected.

Example:
// Assume $repo is a valid EntityRepository and $value is some scalar value.
$qb = $repo->createQueryBuilder('T1')->join('T1.field', 'T2');

$criteria = new Comparison('T2.field2', Comparison::EQ, $value);

$qb->addCriteria($criteria);
$dql = $qb->getDQL();

$dql is now (roughly) equal to:
SELECT T1 FROM <entityclass> T1 JOIN T1.field T2 WHERE T1.T2.field2 = <value>

Evaluating this causes QueryExceptions to be thrown; usually something along the lines of "Expected Doctrine\ORM\Query\Lexer::<token>, got '.'"

There's a similar issue involving ordering by a related field for the same reason.






[DDC-3105] Doctrine Console Error (ORMPurger) Created: 29/Apr/14  Updated: 29/Apr/14

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

Type: Bug Priority: Major
Reporter: Carlos Mendoza Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: Cli, schematool


 Description   

In symfony2 the command doctrine:fixtures:load Fails One-To-Many, Self-referencing using Doctrine\Common\DataFixtures\Purger\ORMPurger in example:

class DescriptionArea

{ //.. /** * @ORM\OneToMany(targetEntity="DescriptionArea", mappedBy="parent") */ protected $descriptionAreas; /** * @ORM\ManyToOne(targetEntity="DescriptionArea", inversedBy="descriptionAreas") */ protected $parent; //.. }

Throw error:
[Doctrine\DBAL\DBALException]

An exception occurred while executing 'DELETE FROM prefix_DescriptionArea':

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (sigtec_dev.prefix_DescriptionArea,

CONSTRAINT FK_7265873E727ACA70 FOREIGN KEY (parent_id) REFERENCES prefix_DescriptionArea (id))

Before running the query should delete the index when the table has self-reference.






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

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

Type: Bug Priority: Major
Reporter: Bruno Jacquet Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 2
Labels: None
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-3098] [GH-1016] improved error handling for invalid association values Created: 23/Apr/14  Updated: 23/Apr/14

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

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


 Description   

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

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

Message:

Possibly to do:
1. Make custom Exception for line 713
2. Make custom Exception for line 817
3. Does the object check on line 816 slow down the code too much? Alternatively a try-catch could be put around line 1415 or higher up.






[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-2783] EntityManager::transactional empty values as true Created: 07/Nov/13  Updated: 18/Apr/14

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

Type: Improvement Priority: Major
Reporter: Kirill chEbba Chebunin Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: entitymanager, transactional


 Description   

The problem:
Any response from transactional callback which is evaluated to false (empty array, empty string, 0, null, etc) becomes true

$return = call_user_func($func, $this);

$this->flush();
$this->conn->commit();

return $return ?: true;

There is the old resolved issue DDC-1336, which describes this behavior.
@return tag is clear now.

@return mixed Returns the non-empty value returned from the closure or true instead

But this logic is blowing mind and leading to unexpectable results. The expected behavior is just return callback result, i don't see any good use cases for current implementation.

It requires a BC break. Can the deprecation process be started to change this behaviour in few major releases?



 Comments   
Comment by Christophe Coevoet [ 07/Nov/13 ]

I agree that this makes the method hard to use. And I don't undertstand why it would replace the return value.

What was the intention for this Benjamin ?

Comment by Guilherme Blanco [ 18/Apr/14 ]

Christophe Coevoet Benjamin Eberlei I'm considering to remove the ternary and always return the callback result.
What do you think? It seems like a minor BC break, but would like to get more feedback around this.

Comment by Marco Pivetta [ 18/Apr/14 ]

Guilherme Blanco this was already refused before because of the BC break.





[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-585] Create a coding standards document Created: 13/May/10  Updated: 17/Apr/14

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

Type: Documentation Priority: Major
Reporter: Roman S. Borschel Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

We need a new coding standards document for Doctrine 2.



 Comments   
Comment by Benjamin Morel [ 29/Jan/13 ]

Has there been any work on a coding standards document yet?
I'm currently working on fixing documentation on this project, and it might be a good time to define a standard.
I've started compiling a few recommendations based on various feedbacks I've got in my pull requests, and I can post them here.
Please let me know if there have been previous attempts so far!

Comment by Marco Pivetta [ 29/Jan/13 ]

Benjamin Morel Guilherme Blanco may have a CS ruleset, but it's not ready yet. Perfect timing btw, we really need to automate this to avoid having all these useless CS fix comments in pull requests

Comment by Benjamin Morel [ 29/Jan/13 ]

Ok, I'll post my document here once ready, and Guilherme Blanco will be able to compare it with his ruleset!

Comment by Benjamin Morel [ 30/Jan/13 ]

Here is a first draft: https://gist.github.com/4676670

Please comment!

Comment by Benjamin Morel [ 11/Feb/13 ]

Guilherme Blanco, if you don't have time to compare your ruleset with my draft, maybe you could publish your current ruleset so that others can have a look?

Comment by Benjamin Morel [ 02/Aug/13 ]

Any update guys? I'm willing to spend some time on this work, but if no one answers, we won't be going forward

Comment by Marco Pivetta [ 02/Aug/13 ]

Benjamin Morel I think a pull request against the doctrine website (https://github.com/doctrine/doctrine-website-sphinx) would be fine...

Comment by Steve Müller [ 17/Apr/14 ]

This should go into https://github.com/doctrine/coding-standard repo (long term).





[DDC-536] Remove the _ prefix from private and protected members Created: 23/Apr/10  Updated: 16/Apr/14

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

Type: Improvement Priority: Major
Reporter: Roman S. Borschel Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 1
Labels: None


 Description   

The reasoning is simple: The prefix "_" is usually either used for easier distinction of instance variables from other, i.e. local variables, instead of always using "this." (often seen in C#), or it is used to signal that a member is not meant to be accessed from outside of the class when the language does not have visibility modifiers (PHP4).

Since you always have to use "$this->" in PHP5+ when accessing instance members and there are visibility modifiers, the "_" is largely superfluous and just makes the verbose OO code even more verbose.

Maybe the following find/replace steps will do the job almost completely:

"private $_" => "private $"
"protected $_" => "protected $"
"$this->_" => "$this->"


 Comments   
Comment by Benjamin Eberlei [ 27/Apr/10 ]

i just found a possible BC issue with this.

EntityRepository is allowed to be extended by us, it has several variables that are underscore prefixed. How to proceed in this case?

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

I know but its not really a problem I think. We should just decide whether we make them private in the first place and provide getters instead (which would have avoided this problem in the first place).

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

Leaving the prefixes on the repository class only is also an option... but I dont think thats necessary.

Comment by Benjamin Eberlei [ 27/Apr/10 ]

can we commit getters for Beta 1 then? We could give everyone a period until Beta 2 to fix their code and then make the change.

EntityRepository is the only class that is meant to be userland extendable to my knowledge, so this should be the only problem to adress

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

Yes, you can add getters and commit right away if you want. Plus adding a note on the upgrade document that direct access of these properties is deprecated.

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

Persisters will be also extensible some day in userland but they need more polish for that, I've already started with it

Comment by Johnny Peck [ 19/Nov/10 ]

Is this still planned? Searching the code base finds this is not being implemented. It would be a good idea to implement the change sooner than later if it will be done at all. Also, +1 for the change. It makes complete sense.

Comment by Guilherme Blanco [ 16/Apr/14 ]

Moving to 3.0 as this can potentially create BC breaks





[DDC-1963] Remove by-ref access to changeset in lifecycle event args Created: 31/Jul/12  Updated: 16/Apr/14

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

Type: Improvement Priority: Major
Reporter: Marco Pivetta Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: None


 Description   

UoW currently passes computed changesets to lifecycle event args byref. This has to be changed to force users to use UoW public API to modify changesets instead.






[DDC-1852] Doctrine\ORM\Tools\SchemaValidator should check validity of lifecycle callbacks Created: 04/Jun/12  Updated: 16/Apr/14

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

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


 Description   

The schema validator should analyze mapped lifecycle callbacks and:

a) if some lifecycle callbacks were defined, but no @HasLifecycleCallbacks annotation/mapping was set, warn the user
b) if some lifecycle callbacks were defined, but methods are not public, warn the user



 Comments   
Comment by Marco Pivetta [ 04/Jun/12 ]

Existing PR at https://github.com/doctrine/doctrine2/pull/361





[DDC-3088] EntityManager::clear doesn't working with inserting Created: 16/Apr/14  Updated: 16/Apr/14

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

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

PHP 5.4.25-1+sury.org~precise+2 (cli) (built: Feb 12 2014 10:45:30)
Symfony version 2.4.2 - app/dev/debug



 Description   

It looks like EntityManager's clear() method doesn't remove objects that was persisted during script execution.

Bellows are two functions. First one insert 10.000 records and use clear after each flush that should remove objects from memory, but instead of that memory usage growths in each iteration. There isn't any other reference for this objects.

I've checked how it works for reading and with clearing it works perfectly - script uses only constant memory.

 
    private function testInserting($em, $entityClass, $batchSize, $startMemoryUsage)
    {
        for ($i = 1; $i <= 10000; ++$i) {

            $item = new $entityClass();
            $item->setName($i);
            $item->setPresentation($i);
            $em->persist($item);

            if ($i % $batchSize == 0) {
                $em->flush();
                $em->clear();

                $currentMemoryUsage = memory_get_usage();
                printf("%d:\n\t%.2f MB (%.2f MB)\n", $i, $currentMemoryUsage /1024 / 1024, ($currentMemoryUsage - $startMemoryUsage) / 1024 / 1024);
            }
        }
    }
    
    
private function testReading($em, $entityClass, $batchSize, $startMemoryUsage)
    {
        $q = $em->createQuery("select i from $entityClass i");
        $iterableResult = $q->iterate();

        $i = 0;
        while (($row = $iterableResult->next()) !== false) {
            $em->clear();
            if ($i % $batchSize == 0) {
                $currentMemoryUsage = memory_get_usage();
                printf("%d:\n\t%.2f MB (%.2f MB)\n", $i, $currentMemoryUsage /1024 / 1024, ($currentMemoryUsage - $startMemoryUsage) / 1024 / 1024);
            }

            $i++;
        }
    }
    

My results:

1) Reading without clearing ($em->clear(); removed)

0:
22.89 MB (2.63 MB)
1000:
33.41 MB (13.15 MB)
2000:
44.04 MB (23.78 MB)
3000:
53.50 MB (33.24 MB)
4000:
65.13 MB (44.86 MB)
5000:
74.81 MB (54.55 MB)
6000:
84.27 MB (64.01 MB)
7000:
97.96 MB (77.69 MB)
8000:
107.40 MB (87.14 MB)
9000:
117.17 MB (96.91 MB)
10000:
126.61 MB (106.35 MB)

2) Reading with using clear

0:
22.89 MB (2.63 MB)
1000:
26.25 MB (5.99 MB)
2000:
24.74 MB (4.48 MB)
3000:
26.72 MB (6.46 MB)
4000:
24.79 MB (4.52 MB)
5000:
26.76 MB (6.50 MB)
6000:
24.81 MB (4.55 MB)
7000:
26.77 MB (6.51 MB)
8000:
24.83 MB (4.57 MB)
9000:
26.81 MB (6.54 MB)
10000:
24.86 MB (4.60 MB)

3) Inserting without clearing

1000:
29.50 MB (9.24 MB)
2000:
37.76 MB (17.50 MB)
3000:
45.12 MB (24.86 MB)
4000:
54.34 MB (34.07 MB)
5000:
61.79 MB (41.53 MB)
6000:
69.09 MB (48.82 MB)
7000:
76.40 MB (56.13 MB)
8000:
83.75 MB (63.48 MB)
9000:
95.64 MB (75.37 MB)
10000:
102.98 MB (82.71 MB)

4) Inserting with using clear

1000:
27.90 MB (7.63 MB)
2000:
34.64 MB (14.37 MB)
3000:
40.43 MB (20.17 MB)
4000:
48.20 MB (27.93 MB)
5000:
54.12 MB (33.85 MB)
6000:
59.89 MB (39.63 MB)
7000:
65.67 MB (45.40 MB)
8000:
71.43 MB (51.16 MB)
9000:
81.51 MB (61.25 MB)
10000:
87.29 MB (67.02 MB)



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

Would be useful to see what the entity class looks like.

Additionally, the ORM version being affected is also needed.





[DDC-1954] Specialized Batch Insert Mode for the Entity Manager Created: 29/Jul/12  Updated: 16/Apr/14

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

Type: Bug Priority: Major
Reporter: Johannes Schmitt Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

While it is already possible to speed up batch inserts by using raw SQL, that has the disadvantage to maintain a separate set of code that needs to be kept in sync with your schema.

Therefore, it would be nice if the entity manager would provide a special batch insert mode where it can skip the change tracking related features, collection snapshots, etc. This might already be good enough for many people.






[DDC-2637] [GH-769] Add Custom Persisters Created: 28/Aug/13  Updated: 15/Apr/14

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

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

Issue Links:
Duplicate
is duplicated by DDC-2629 [GH-768] DDC-391: Add support to conf... Resolved
Reference
relates to DDC-391 Allow to specifiy custom Entity and C... In Progress

 Description   

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

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

Message:

Adding support for custom persisters as defined by DDC-391.
Implementing both Entity and Collection based Persisters



 Comments   
Comment by Doctrine Bot [ 02/Jan/14 ]

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

Comment by Doctrine Bot [ 15/Apr/14 ]

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





[DDC-3083] Persist/Flush silently fails when CTI is applied on an existing table Created: 12/Apr/14  Updated: 13/Apr/14

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

Type: Bug Priority: Major
Reporter: Frank Liepert Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Given an existing table (= parent table) the integration of a new parent-child relationship with Class Table Inheritance (CTI) leads to a update problem.

First of all a child table is created with a foreign key to the parent table. Next, the discriminator column is added to the parent table. The discriminator map will be auto-generated.

The problem arises when trying to perform persist() and flush() on a child entity. Initially the child table is logically empty. However, the UnitOfWork triggers updateTable() which will fail since there is nothing to update. Instead, an upsert should be performed.

Another sneaky thing is that the repository will return the child class with the updated data after calling flush() on the same request. On the next request the child class is returned with the data loaded from the persister. Of course, the updated data is missing.



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

Frank Liepert do I understand this correctly if I say that you are trying to (pseudo) upcast an entity to a more specific subtype? That is unsupported by the ORM. Could you make just an example snippet of what you described in the issue?

Comment by Frank Liepert [ 13/Apr/14 ]

Marco Pivetta: You have understood really well. If you say that's not supported by the ORM then this is the answer. Still I think that upsert could solve solve the "problem" and I know that there are/have been discussions about upsert.

Right now I will continue to manually insert the missing rows in the child table. After this necessary step the ORM works as expected.

Nevertheless the real bug is that after persist() and flush() the entity manager returns the child object with the "persisted" data of the child table although there are in fact no rows in the child table.

$parentRepository = $em->getRepository('Parent');

$child = $parentRepository ->find(1);
$child->setChildPropertyA('foo');

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

$child = $parentRepository ->find(1);
var_dump($child->getChildPropertyA());
// string(3) "foo"

// But: There is no 'foo' in the child table!


/** 
 * NEW REQUEST
 */

$parentRepository = $em->getRepository('Parent');

$child = $parentRepository ->find(1);
var_dump($child->getChildPropertyA());
// NULL

Comment by Marco Pivetta [ 13/Apr/14 ]

Frank Liepert why are $child in the first request and $child in the second request different here? Are you manually changing the data at SQL level?

Comment by Frank Liepert [ 13/Apr/14 ]

Marco Pivetta as I have explained the persist() and flush() in the first request trigger an UPDATE command (Because there is already a row in the parent table?). Given that the child table was manually created before there are no rows on that table at that time and therefore nothing can be updated. Nevertheless the ORM triggers no error and $child looks like having been persisted. In the second request you'll notice that there haven't been persisted any of the data belonging to the child table.





[DDC-3079] preUpdate in EntityListener not run in transaction Created: 10/Apr/14  Updated: 10/Apr/14

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

Type: Bug Priority: Major
Reporter: Jiri Napravnik Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

I have entity:

class Article{
	/**
	 * @ORM\OneToMany(targetEntity = "ArticleModule\Model\Entities\ArticlePhoto", mappedBy = "article", cascade = {"persist", "remove"}, orphanRemoval = TRUE)
	 * @ORM\OrderBy({"sequence" = "ASC"})
	 */
	protected $articlePhotos;
}

And Entity Listener with preRemove.

I call

$article->articlePhotos->clear();
...some changes with entity...
$em->flush();

preRemove in Entity Listener is called, BUT before Begin transaction...

I can do
$em->transactional(function(){}); then it's full in transaction..






[DDC-3005] Events::postLoad fires without filled associations Created: 02/Mar/14  Updated: 10/Apr/14

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

Type: Bug Priority: Major
Reporter: Artur Eshenbrener Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: None


 Description   

When we load entities throw one dql query like this:

SELECT e, joined_link FROM Entity LEFT JOIN e.link joined_link

In event subscriber, subscribed to postLoad event for instances of Entity property "link" of entity does not contains fetched in same query joined entity, and does not contains proxy object.

Tell me if failing test case needed.



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

The postLoad event is fired without warranty that association entities/proxies will be set:

http://docs.doctrine-project.org/en/latest/reference/events.html#lifecycle-events

Comment by Artur Eshenbrener [ 03/Mar/14 ]

But why? This shounds like involuntary restriction, and I think it can be fixed. Will my PR with fix accepted, or collaborators don't want to change this behaviour?

Comment by Marco Pivetta [ 03/Mar/14 ]

Artur Eshenbrener triggering `postLoad` in the correct moment in time (when all dependencies are loaded) requires a lot of additional complexity to be inserted in various locations of the ORM.

Since `postLoad` is supposed to be used like `__wakeup` and in general for simple tasks, this kind of refactoring/rewrite would be an overkill.

Comment by Artur Eshenbrener [ 04/Mar/14 ]

> requires a lot of additional complexity to be inserted in various locations of the ORM.
Sounds like "It is very hard to implement, and no one want to do this"

> and in general for simple tasks, this kind of refactoring/rewrite would be an overkill.
Disagree with this. Why only simple? I need to deal with associations in this event. Without this I should inject whole EntityManager to my entity, but I dont want to do this.

And I forced to repeat the question: will PR with fix accepted or not?

Comment by Marco Pivetta [ 04/Mar/14 ]

Sounds like "It is very hard to implement, and no one want to do this"

Not really, the main problem here is performance, since hydration would have to be completely redesigned.
Yes, "too hard" is a good reason for something that is an edge case.

And I forced to repeat the question: will PR with fix accepted or not?

Sure thing! Just needs to avoid a massive rewrite though.

Comment by Marco Pivetta [ 04/Mar/14 ]

To give you some hints, Doctrine\ORM\Events::postLoad is triggered in https://github.com/doctrine/doctrine2/blob/15432fc55f83c2d6ce8d9b86fd3139dd2a4fc328/lib/Doctrine/ORM/UnitOfWork.php#L2788, and Doctrine\ORM\UnitOfWork#createEntity() is used by all the various hydrators internally.

To ensure that Doctrine\ORM\Events::postLoad is triggered after an entity is fully loaded, the various hydrators must trigger the events after being sure that all data has been set, and that the entity is "ready" for use. That's some copy-paste work :\

Comment by Artur Eshenbrener [ 04/Mar/14 ]

I think the entry point is here: https://github.com/doctrine/doctrine2/blob/15432fc55f83c2d6ce8d9b86fd3139dd2a4fc328/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php#L140,
so, copy-paste work is not needed )

Comment by Artur Eshenbrener [ 05/Apr/14 ]

PR is ready: https://github.com/doctrine/doctrine2/pull/1001





[DDC-3070] [GH-1001] [DDC-3005] Defer invoking of postLoad event to the end of hydration cycle. Created: 04/Apr/14  Updated: 04/Apr/14

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

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


 Description   

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

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

Message:

This feature makes guarantee, that postLoad event fires after all associations are populated.
Test case also provided.






[DDC-1721] LIKE clausule should accept functions on the pattern Created: 21/Mar/12  Updated: 01/Apr/14

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

Type: Improvement Priority: Major
Reporter: Ignacio Larranaga Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 2
Labels: querybuilder,, sql-walker

Attachments: Text File Parser.patch     Text File SqlWalker.patch    

 Description   

Example:
SELECT .... WHERE upper(n.title) LIKE upper(:filter)

should be a valid SQL, now is rejected because the walker only accept a variable or an string expression.

I'm adding a patch to address this.



 Comments   
Comment by Ignacio Larranaga [ 21/Mar/12 ]

Sorry the Parser has to be modified also to allow expressions to be recognized, I'm attaching the necessary patch.

Comment by Benjamin Eberlei [ 22/Mar/12 ]

I am sure there is a reason why the walker doesn't accept this such as not all supported vendors allowing functions in right hand side LIKE expressions, but i am not sure about this.

Comment by Glen Ainscow [ 03/Oct/12 ]

This is not possible either:

WHERE CASE WHEN p.name IS NULL THEN u.username ELSE p.name END LIKE :name

Comment by Thomas Mayer [ 24/Jan/13 ]

In my case it worked when using "=" instead of "LIKE".

//works:
(CASE WHEN (Book.id = BookFrom.id) THEN BookTo.displayName ELSE BookFrom.displayName END) = :name

//[Syntax Error] line 0, col 1217: Error: Expected =, <, <=, <>, >, >=, !=, got 'LIKE'
(CASE WHEN (Book.id = BookFrom.id) THEN BookTo.displayName ELSE BookFrom.displayName END) LIKE :name

So the LIKE operator only needs to be allowed here.

I'm wondering which vendor should not be able to handle that:
The CASE WHEN ... THEN ... END is documented in DQL, and allowed.
LIKE itself is allowed.
If an RDBMs cannot use CASE WHEN and LIKE in combination, this would be a strange limitation.

Comment by Martin Keckeis [ 31/Mar/14 ]

Having the same problem here.

LIKE + CASE is often used in my application at the WHERE part.
(e.g. data filtering of a datagrid column)





[DDC-2042] Metadata association overriding : allow to override 'targetEntity' Created: 26/Sep/12  Updated: 31/Mar/14

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

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


 Description   

While associating object to an descriminated table I wasn't enable to fix the entityTarget (only one can be set in entity annotation).

It could be resolve by adding the possibility to override 'targetEntity' value in Doctrine\ORM\Mapping\ClassMetadataInfo::ClassMetadataInfo().

Such as :

if (isset($overrideMapping['targetEntity'])) {
$mapping['targetEntity'] = $overrideMapping['targetEntity'];
}

That would need to add a control on the new targetEntity in Doctrine\ORM\Mapping\ClassMetadataInfo::_validateAndCompleteAssociationMapping().

Such as :

if ( ! ClassLoader::classExists($mapping['targetEntity']) ) {
throw MappingException::invalidTargetEntityClass($mapping['targetEntity'], $this->name, $mapping['fieldName']);
}

cro.



 Comments   
Comment by Oleg Namaka [ 31/Mar/14 ]

We need this feature too. Why is this ticket in a limbo? Someone please add a comment whether this will be fixed.

Comment by Marco Pivetta [ 31/Mar/14 ]

Oleg Namaka you can open a pull request with a test and suggested improvement for this at https://github.com/doctrine/doctrine2





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

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

Type: Bug Priority: Major
Reporter: Andy hunt Assignee: Benjamin Eberlei
Resolution: Unresolved 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





[DDC-2363] Duplicated record with orphanRemoval and proxy Created: 22/Mar/13  Updated: 27/Mar/14

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

Type: Bug Priority: Major
Reporter: Manuele Menozzi Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: orphanRemoval, proxy
Environment:

Tested both Mac OS X and Ubuntu


Issue Links:
Duplicate
is duplicated by DDC-2364 [GH-625] [DDC-2363] Duplicated record... Open

 Description   

There is a problem that causes duplicate records are created when EntityManager has to remove an entity due to orphanRemoval. The problem occurs only with a double flush and referred object is a proxy.

I'm trying to submit a pull request for this ticket. Please, stand by.



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

Hey Manuele Menozzi, do you remember if this has been fixed? Are you still able to reproduce the problem?

Comment by Manuele Menozzi [ 27/Mar/14 ]

Hi Marco,
I made a PR (https://github.com/doctrine/doctrine2/pull/625) with an automated test that reproduce the problem. I just ran this test over latest version of doctrine2 and it's still failed. So, the problem has not be fixed and I (or you) can reproduce it easily.

Let me know if I can help you somehow.

Comment by Marco Pivetta [ 27/Mar/14 ]

Thanks, didn't see it!





[DDC-2452] Additional `WITH` condition in joins between JTI roots cause invalid SQL to be produced Created: 16/May/13  Updated: 27/Mar/14

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

Type: Bug Priority: Major
Reporter: Marco Pivetta Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: dql, sql-walker
Environment:

irrelevant



 Description   

Given a simple Joined Table Inheritance like following:

/**
 * @Entity @Table(name="foo") @InheritanceType("JOINED")
 * @DiscriminatorColumn(name="discr", type="string")
 * @DiscriminatorMap({"foo" = "DDC2452Foo", "bar" = "DDC2452Bar"})
 */
class DDC2452Foo
{
    /** @Id @Column(type="integer") @GeneratedValue */
    public $id;
}

/** @Entity @Table(name="bar") */
class DDC2452Bar extends DDC2452Foo
{
}

Following DQL

SELECT foo1 FROM DDC2452Foo foo1 JOIN DDC2452Foo foo2 WITH 1=1

Will produce broken SQL:

SELECT
    f0_.id AS id0, f0_.discr AS discr1 
FROM 
    foo f0_ 
LEFT JOIN bar b1_ 
    ON f0_.id = b1_.id 
LEFT JOIN foo f2_ 
LEFT JOIN bar b3_ 
    ON f2_.id = b3_.id 
    ON (1 = 1)

(please note the duplicate `ON` in the SQL)

That is caused because of the SQL walker producing the JTI filter with already the `ON` clause in it.

That happens because the JTI join conditions are added in https://github.com/doctrine/doctrine2/blob/2.4.0-BETA2/lib/Doctrine/ORM/Query/SqlWalker.php#L823-L825 (`walkRangeVariableDeclaration`), while the additional defined `WITH` conditions are considered in `walkJoinAssociationDeclaration` later on.

Added a test case and fix at https://github.com/doctrine/doctrine2/pull/668






[DDC-2590] Class inheritance - left join between child and parent entities Created: 06/Aug/13  Updated: 25/Mar/14

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

Type: Bug Priority: Major
Reporter: Tomáš Ďuračka Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: inheritance, joins, orm, sql-walker


 Description   

The piece of code given under creates wrong sql to me.

Module is parent entity for BusinessModule entity. Category is joined with BusinessModule.

Module entity is only left joined to its child entity and that's the problem because it contains a field "name" used for filtering. So even if there is no module having the name, categories are still included.

I need the parent entity to be inner joined to child entity not left joined.

File doctrine2/lib/Doctrine/ORM/Query/SqlWalker.php line 353:

// If this is a joined association we must use left joins to preserve the correct result.
$sql .= isset($this->queryComponents[$dqlAlias]['relation']) ? ' LEFT ' : ' INNER ';
$qb->select('c')
->from('Category', 'c')
->join('c.module', 'm', 'WITH', 'm.name = :moduleName')
->setParameter('moduleName', $moduleName);
SELECT c0_.category_id AS category_id0, c0_.title AS title1, c0_.h1 AS h12, c0_.alias AS alias3,
c0_.insertion_fee AS insertion_fee4, c0_.description AS description5, c0_.parent_category_id AS
parent_category_id6, c0_.module_id AS module_id7 
FROM category c0_ 
INNER JOIN business_module b1_ ON c0_.module_id = b1_.module_id 
LEFT JOIN module m2_ ON b1_.module_id = m2_.module_id AND (m2_.name = ?)


 Comments   
Comment by Marek Štípek [ 06/Nov/13 ]

I am experiencing the same issue. The workarround could be to use LEFT JOIN with IS NOT NULL condition... But it also doesnt work after this commit
https://github.com/doctrine/doctrine2/commit/d9c1782a4f6d46f66e9deb2c375830f9192d4482 (i had to revert to dev-master#13c1efb240dd0af25ad0abe230df98ec895892c7)





[DDC-3046] The flushed data is not available immediately for querying Created: 25/Mar/14  Updated: 25/Mar/14

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

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

ubuntu 13.10, mysql 5.5.35



 Description   

Doctrine's persisted data is not accessible by other queries immediately, for details see http://stackoverflow.com/questions/22618689/doctrines-persisted-data-is-not-accessible-by-other-queries-immediately






[DDC-2982] [GH-954] Multi Get support for Second Level Cache Created: 14/Feb/14  Updated: 23/Mar/14

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

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


 Description   

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

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

Message:

Hi!
As discussed [here](http://www.doctrine-project.org/jira/browse/DDC-2981) i have implemented some kind of multi-get for second level cache implementation.

I have also created a PR to doctrine/cache component (see https://github.com/doctrine/cache/pull/29) that enables this feature at driver cache level.






[DDC-2983] TCI association not getting hydrated into sql statement Created: 14/Feb/14  Updated: 23/Mar/14

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

Type: Bug Priority: Major
Reporter: Machete Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: orm
Environment:

MySQL, using DoctrineORMModule (zf2 integration)



 Description   

/**
 * @ORM\Entity
 * @ORM\Table(name="base")
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="discriminator", type="string")
 * @ORM\DiscriminatorMap({
 * "a" = "A",
 * "b" = "B",
 * })
 */
class Base
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
}

/**
 * @ORM\Entity
**/
class A extends Base {
    /**
     * @ORM\ManyToOne(targetEntity="B", inversedBy="as")
     */
    protected $b;

    /**
     * @ORM\OneToMany(targetEntity="C", cascade={"persist"})
     */
    protected $cs;
}

/**
 * @ORM\Entity
**/
class B Extends Base {
    /**
     * @ORM\OneToMany(targetEntity="A", mappedBy="b")
     */
    protected $as;
}

/**
 * @ORM\Entity
**/
class C {
  // ...
}

Doing this:

$a = new A();
$b = new B();

$a->setB($b);
$b->addA($a);

var_dump($a->getB()); // outputs B (b not null!)
var_dump($b->getAs()) // outputs A (private $_elements => [0] class B)

$em->persist($a);
$em->persist($b);
$em->flush();

Leads to

integrity constraint violation, b_id can not be null

aka

INSERT INTO a (id, b_id), (123, null);

I have no idea why this happens. This works:

$a = new A();
$b = new B();

$a->setB($b);
$b->addA($a);

var_dump($a->getB()); // outputs B (b not null!)
var_dump($b->getAs()) // outputs A (private $_elements => [0] class B)

$em->persist($a);
$em->flush();
$em->persist($b);
$em->flush();


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

This most likely happens because the UnitOfWork tries to set the owner and reverse incorrectly due to an ordering issue.





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

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





[DDC-1714] Prevent inverse side lazy loading owning side of the oneToOne relationsip if owning side's id is an assosiationKey of inversed side Created: 18/Mar/12  Updated: 23/Mar/14

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

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


 Description   

This issue was originally discussed in http://www.doctrine-project.org/jira/browse/DDC-357

Say there is User and UserData with oneToOne bidirectional relationship. When we fetch User objects, UserData is lazy loaded right away.

If we were to set UserData 's id as asssosiationKey of User, then user_id becomes the id of UserData and User object can already know that UserData owning side's id will equal it's own User->id.

Can this be implemented?



 Comments   
Comment by Doctrine Bot [ 23/Mar/14 ]

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





[DDC-3044] [GH-986] Add last modified time for metadata Created: 22/Mar/14  Updated: 22/Mar/14

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

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


 Description   

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

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

Message:

This patch improves performance during development and does not affect production performance.

Currently, enabling the metadata cache during development gives a remarkable performance boost, but it requires that you manually flush the metadata cache when the metadata has been changed. When running console commands such as ``console orm:schema-tool:update`` (see #979).

With this change, metadata entries fetched from cache are checked for freshness using a quick last modified check. This is much faster than loading the actual metadata using the metadata driver. This allows you to enable the metadata cache during development without the need for manually flushing the metadata cache.

This PR is part 1 of 2. Part 2 is for the doctrine/common repository.

If this PR is accepted, it allows us to optimize the auto-generate proxy classes feature by comparing the last modified time for the metadata with the modified timestamp of the generated file.






[DDC-3036] [doctrine:generate:entities] Created: 17/Mar/14  Updated: 17/Mar/14

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

Type: Improvement Priority: Minor
Reporter: Miguel Simões Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: orm


 Description   

When using an Entity that is extended by some other class (that may not be a Doctrine Entity), the command doctrine:generate:entities should not create getters/setters that are already defined in the parent class.






[DDC-3029] DISTINCT , ORDER BY AND Limit in SQL Server Created: 14/Mar/14  Updated: 14/Mar/14

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

Type: Bug Priority: Major
Reporter: Michał Banaś Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None

Attachments: File SQLServerPlatform.php    

 Description   

I don't know if I should report it here , becouse error is in SQLServerPlatform.php file.
basicaly Distinct includes ROWNUM()
So if you add distinct in DQL it will be translated to "select distinct ...... , Rownum()" - which is always distinct offcource.

Here is original version
protected function doModifyLimitQuery($query, $limit, $offset = null)
{
if ($limit > 0) {
if ($offset == 0)

{ $query = preg_replace('/^(SELECT\s(DISTINCT\s)?)/i', '\1TOP ' . $limit . ' ', $query); }

else {
$orderby = stristr($query, 'ORDER BY');

if ( ! $orderby)

{ $over = 'ORDER BY (SELECT 0)'; }

else

{ $over = preg_replace('/\"[^,]*\".\"([^,]*)\"/i', '"inner_tbl"."$1"', $orderby); }

// Remove ORDER BY clause from $query
$query = preg_replace('/\s+ORDER BY(.*)/', '', $query);
$query = preg_replace('/^SELECT\s/', '', $query);

$start = $offset + 1;
$end = $offset + $limit;

$query = "SELECT * FROM (SELECT ROW_NUMBER() OVER ($over) AS doctrine_rownum, $query) AS doctrine_tbl WHERE doctrine_rownum BETWEEN $start AND $end";
}
}

return $query;
}
In Attachenment there is a fixed version of this file.






[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-3025] Schema tool UPDATE or CREATE not generate decimal precision and scale for ID element Created: 12/Mar/14  Updated: 12/Mar/14

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

Type: Bug Priority: Major
Reporter: huda salam Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

FYI. I don't use doctrine but with symfony2, and only use .yml or .xml mapping. Not yet try with annotation.

These commands :

php app\console doctrine:schema:update
php app\console doctrine:schema:create

Will not generate id's precision and scale for this kind of mapping :

<doctrine-mapping .....>
  <entity name="Namespace\MyBundle\Entity\MyData" table="my_data">
    <id name="id" type="decimal" column="id" precision="x" scale="y">
      <generator strategy="IDENTITY"/>
    </id>
    <field ... />
  </entity>
</ ....>

Suggested changes :

  • Doctrine\ORM\Mapping\Driver\YamlDriver.php
  • Doctrine\ORM\Mapping\Driver\XmlDriver.php





[DDC-2184] [GH-530] Singular form of generated methods should end with 'y' when property ends with 'ies' Created: 04/Dec/12  Updated: 05/Mar/14

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

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

Issue Links:
Duplicate
duplicates DDC-2150 EntityGenerator.php - Guessing singul... Resolved
duplicates DDC-2160 [GH-520] Fix for Doctrine\ORM\Tools\E... Resolved

 Description   

In Doctrine 2.3 the 'add' and 'remove' methods in oneToMany associations have another problem (in earlier versions like 2.2 this worked correct). The singular form is not correctly detected if the property ends with 'ies' like 'entries' which should be transformed to 'entry'.
I have this YAML definition:

Archive:
  type: entity
  fields:
    id:
      id: true
      type: integer
      unsigned: false
      nullable: false
      generator:
        strategy: IDENTITY
  oneToMany:
    entries:
      targetEntity: Entry
      mappedBy: archive

This generates these methods:

public function addEntrie(\Entry $entries) { ... }
public function removeEntrie(\Entry $entries) { ... }

Because in the EntityGenerator only the plural 's' is removed. It would be nice if an ending of 'ies' could be replaced by 'y'. So that we get these methods

public function addEntry(\Entry $entries) { ... }
public function removeEntry(\Entry $entries) { ... }

My fork already has the changes https://github.com/naitsirch/doctrine-orm2/commit/a3adfccb4927d61da7debae46ed0fff61e4212f8
I have opened a pull request here https://github.com/doctrine/doctrine2/pull/530



 Comments   
Comment by Christian Stoller [ 04/Dec/12 ]

Sorry, I accidently clicked on the button 'Request Feedback'
Now the status has changed to 'Awaiting Feedback'

Comment by Benjamin Eberlei [ 06/Jan/13 ]

Mark as improvement

Comment by Ed Page Croft [ 04/Jul/13 ]

Is this issue going to be resolved? It's a major problem for our project - a stock market application that uses properties like 'securities' and entities of name 'Security'.

Comment by Doctrine Bot [ 05/Mar/14 ]

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





[DDC-3007] ManyToMany does not respect all column attributes for the jointable Created: 03/Mar/14  Updated: 03/Mar/14

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

Type: Bug Priority: Major
Reporter: Michael Kühn Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Given following 2 entities:

<?php
class Role {
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="UUID")
     * @ORM\Column(name="id", type="guid", nullable=false, unique=true, length=36, options={"fixed"=true})
     */
    protected $id;

    /**
     * @ORM\ManyToMany(targetEntity="User", mappedBy="roleList")
     */
    private $userList;
}
<?php
class User {
    /**
     * @ORM\Column(name="id", type="guid", nullable=false, unique=true, length=36, options={"fixed"=true})
     * @ORM\Id
     * @ORM\GeneratedV