Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Store redundant fields in references #1527

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions doctrine-mongo-mapping.xsd
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@
<xs:element name="default-discriminator-value" type="odm:default-discriminator-value" minOccurs="0"/>
<xs:element name="sort" type="odm:sort-map" minOccurs="0" />
<xs:element name="criteria" type="odm:criteria-map" minOccurs="0" />
<xs:element name="redundant-fields" type="odm:redundant-field-list" minOccurs="0" />
</xs:sequence>
<xs:attribute name="target-document" type="xs:string" />
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
Expand All @@ -157,6 +158,7 @@
<xs:element name="default-discriminator-value" type="odm:default-discriminator-value" minOccurs="0"/>
<xs:element name="sort" type="odm:sort-map" minOccurs="0" />
<xs:element name="criteria" type="odm:criteria-map" minOccurs="0" />
<xs:element name="redundant-fields" type="odm:redundant-field-list" minOccurs="0" />
</xs:sequence>
<xs:attribute name="target-document" type="xs:string" />
<xs:attribute name="collection-class" type="xs:string" />
Expand Down Expand Up @@ -184,6 +186,16 @@
</xs:sequence>
</xs:complexType>

<xs:complexType name="redundant-field-list">
<xs:sequence>
<xs:element name="field" type="odm:redundant-field" minOccurs="1" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="redundant-field">
<xs:attribute name="name" type="xs:string" use="required"/>
</xs:complexType>

<xs:complexType name="criteria-type">
<xs:attribute name="field" type="xs:NMTOKEN" use="required"/>
<xs:attribute name="value" type="xs:NMTOKEN" use="required" />
Expand Down
18 changes: 18 additions & 0 deletions lib/Doctrine/ODM/MongoDB/DocumentManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
use Doctrine\ODM\MongoDB\Proxy\ProxyFactory;
use Doctrine\ODM\MongoDB\Query\FilterCollection;
use Doctrine\ODM\MongoDB\Repository\RepositoryFactory;
use Doctrine\ODM\MongoDB\Types\Type;

/**
* The DocumentManager class is the central access point for managing the
Expand Down Expand Up @@ -738,6 +739,23 @@ public function createDBRef($document, array $referenceMapping = null)
$dbRef[$discriminatorField] = $discriminatorValue;
}

if ($referenceMapping !== null && isset($referenceMapping['redundantFields'])) {
foreach ($referenceMapping['redundantFields'] as $fieldName) {
if ($class->hasAssociation($fieldName)) {
throw MappingException::redundantAssociationNotAllowed(get_class($document), $fieldName);
}

if (! $class->hasField($fieldName)) {
throw MappingException::mappingNotFound(get_class($document), $fieldName);
}

$mapping = $class->getFieldMapping($fieldName);
$value = $class->getFieldValue($document, $fieldName);

$dbRef[$fieldName] = Type::getType($mapping['type'])->convertToDatabaseValue($value);
}
}

return $dbRef;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,11 @@ final class ReferenceMany extends AbstractField
public $inversedBy;
public $mappedBy;
public $repositoryMethod;
public $sort = array();
public $criteria = array();
public $sort = [];
public $criteria = [];
public $limit;
public $skip;
public $strategy = CollectionHelper::DEFAULT_STRATEGY;
public $collectionClass;
public $redundantFields = [];
}
5 changes: 3 additions & 2 deletions lib/Doctrine/ODM/MongoDB/Mapping/Annotations/ReferenceOne.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@ final class ReferenceOne extends AbstractField
public $inversedBy;
public $mappedBy;
public $repositoryMethod;
public $sort = array();
public $criteria = array();
public $sort = [];
public $criteria = [];
public $limit;
public $skip;
public $redundantFields = [];
}
8 changes: 8 additions & 0 deletions lib/Doctrine/ODM/MongoDB/Mapping/ClassMetadataInfo.php
Original file line number Diff line number Diff line change
Expand Up @@ -1323,6 +1323,14 @@ public function mapField(array $mapping)
throw MappingException::simpleReferenceRequiresTargetDocument($this->name, $mapping['fieldName']);
}

if (isset($mapping['reference'])
&& isset($mapping['storeAs'])
&& $mapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_ID
&& ! empty($mapping['redundantFields'])
) {
throw MappingException::simpleReferenceCannotHaveRedundantFields($this->name, $mapping['fieldName']);
}

if (isset($mapping['reference']) && empty($mapping['targetDocument']) && empty($mapping['discriminatorMap']) &&
(isset($mapping['mappedBy']) || isset($mapping['inversedBy']))) {
throw MappingException::owningAndInverseReferencesRequireTargetDocument($this->name, $mapping['fieldName']);
Expand Down
6 changes: 6 additions & 0 deletions lib/Doctrine/ODM/MongoDB/Mapping/Driver/XmlDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,12 @@ private function addReferenceMapping(ClassMetadataInfo $class, $reference, $type
if (isset($attributes['also-load'])) {
$mapping['alsoLoadFields'] = explode(',', $attributes['also-load']);
}
if (isset($reference->{'redundant-fields'})) {
foreach ($reference->{'redundant-fields'}->{'field'} as $redundantField) {
$attr = $redundantField->attributes();
$mapping['redundantFields'][] = (string) $attr['name'];
}
}
$this->addFieldMapping($class, $mapping);
}

Expand Down
3 changes: 3 additions & 0 deletions lib/Doctrine/ODM/MongoDB/Mapping/Driver/YamlDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,9 @@ private function addMappingFromReference(ClassMetadataInfo $class, $fieldName, $
if (isset($reference['criteria'])) {
$mapping['criteria'] = $reference['criteria'];
}
if (isset($reference['redundantFields'])) {
$mapping['redundantFields'] = (array) $reference['redundantFields'];
}
$this->addFieldMapping($class, $mapping);
}

Expand Down
20 changes: 20 additions & 0 deletions lib/Doctrine/ODM/MongoDB/Mapping/MappingException.php
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,26 @@ public static function simpleReferenceMustNotTargetDiscriminatedDocument($target
return new self("Simple reference must not target document using Single Collection Inheritance, $targetDocument targeted.");
}

/**
* @param string $className
* @param string $fieldName
* @return MappingException
*/
public static function simpleReferenceCannotHaveRedundantFields($className, $fieldName)
{
return new self("Simple reference $className::$fieldName may not store redundant fields");
}

/**
* @param string $className
* @param string $fieldName
* @return MappingException
*/
public static function redundantAssociationNotAllowed($className, $fieldName)
{
return new self("Association $className::$fieldName can not be stored as redundant field");
}

/**
* @param string $strategy
* @param string $className
Expand Down
16 changes: 16 additions & 0 deletions tests/Doctrine/ODM/MongoDB/Tests/DocumentManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,19 @@ public function testDifferentStoreAsDbReferences()
$this->assertArrayHasKey('$db', $dbRef);
}

public function testDbRefWithRedundantField()
{
$r = new \Documents\User();
$r->setUsername('foo');
$this->dm->persist($r);
$d = new ReferenceStoreAsDocument();
$class = $this->dm->getClassMetadata(get_class($d));

$dbRef = $this->dm->createDBRef($r, $class->associationMappings['ref4']);
$this->assertArrayHasKey('username', $dbRef);
$this->assertSame('foo', $dbRef['username']);
}

private function getMockClassMetadataFactory()
{
return $this->createMock('Doctrine\ODM\MongoDB\Mapping\ClassMetadataFactory');
Expand Down Expand Up @@ -279,4 +292,7 @@ class ReferenceStoreAsDocument

/** @ODM\ReferenceOne(targetDocument="Documents\User", storeAs="dbRefWithDb") */
public $ref3;

/** @ODM\ReferenceOne(targetDocument="Documents\User", storeAs="dbRef", redundantFields={"username"}) */
public $ref4;
}
143 changes: 143 additions & 0 deletions tests/Doctrine/ODM/MongoDB/Tests/Functional/RedundantFieldsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
<?php

namespace Doctrine\ODM\MongoDB\Tests\Functional;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

class RedundantFieldsTest extends \Doctrine\ODM\MongoDB\Tests\BaseTest
{
public function testSimpleRedundantField()
{
$blog = new Blog('my-blog');
$this->dm->persist($blog);

$post = new Post($blog, 'My first post');
$this->dm->persist($post);
$this->dm->flush();

$rawPost = $this->dm->createQueryBuilder(Post::class)
->find()
->field('id')
->equals($post->getId())
->hydrate(false)
->getQuery()
->getSingleResult();

$this->assertSame('my-blog', $rawPost['blog']['title']);
$this->assertInstanceOf(\MongoDate::class, $rawPost['blog']['creationDate']);
}

public function testDatabaseValueIsPreparedInQuery()
{
$blog = new Blog('my-blog');
$this->dm->persist($blog);

$post = new Post($blog, 'My first post');
$this->dm->persist($post);
$this->dm->flush();

$result = $this->dm->createQueryBuilder(Post::class)
->find()
->field('blog.creationDate')
->equals($blog->getCreationDate())
->getQuery()
->execute();

$this->assertCount(1, $result);
}

public function testStoringFieldWorksWithProxy()
{
$blog = new Blog('my-blog');
$this->dm->persist($blog);
$this->dm->flush();

$this->dm->clear();
$blog = $this->dm->getReference(Blog::class, $blog->getId());

$post = new Post($blog, 'My first post');
$this->dm->persist($post);
$this->dm->flush();

$rawPost = $this->dm->createQueryBuilder(Post::class)
->find()
->field('id')
->equals($post->getId())
->hydrate(false)
->getQuery()
->getSingleResult();

$this->assertSame('my-blog', $rawPost['blog']['title']);
$this->assertInstanceOf(\MongoDate::class, $rawPost['blog']['creationDate']);
}
}

/**
* @ODM\Document()
*/
class Blog
{
/** @ODM\Id */
protected $id;

/** @ODM\Field(type="string") */
protected $title;

/** @ODM\Field(type="date") */
protected $creationDate;

public function __construct($title)
{
$this->title = $title;
$this->creationDate = new \DateTime();
}

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

public function getTitle()
{
return $this->title;
}

public function getCreationDate()
{
return $this->creationDate;
}
}

/** @ODM\Document */
class Post
{
/** @ODM\Id */
protected $id;

/** @ODM\ReferenceOne(targetDocument="Blog", redundantFields={"title","creationDate"}) */
protected $blog;

/** @ODM\Field(type="string") */
protected $title;

public function __construct(Blog $blog, $title)
{
$this->blog = $blog;
$this->title = $title;
}

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

public function getBlog()
{
return $this->blog;
}

public function getTitle()
{
return $this->title;
}
}
15 changes: 15 additions & 0 deletions tests/Doctrine/ODM/MongoDB/Tests/Mapping/ClassMetadataInfoTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,21 @@ public function testNoReferenceManyInShardKey()
$cm->mapManyEmbedded(['fieldName' => 'referenceMany']);
$cm->setShardKey(array('referenceMany' => 1));
}

/**
* @expectedException \Doctrine\ODM\MongoDB\Mapping\MappingException
* @expectedExceptionMessage Simple reference stdClass::referenceOne may not store redundant fields
*/
public function testSimpleReferenceWithRedundantFieldsThrowsError()
{
$cm = new ClassMetadataInfo('stdClass');
$cm->mapOneReference([
'fieldName' => 'referenceOne',
'targetDocument' => 'stdClass',
'storeAs' => ClassMetadataInfo::REFERENCE_STORE_AS_ID,
'redundantFields' => ['foo', 'bar'],
]);
}
}

class TestCustomRepositoryClass extends DocumentRepository
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ public function testDriver()
'limit' => null,
'skip' => null,
'orphanRemoval' => false,
'redundantFields' => ['name'],
), $classMetadata->fieldMappings['account']);

$this->assertEquals(array(
Expand Down Expand Up @@ -220,6 +221,7 @@ public function testDriver()
'limit' => null,
'skip' => null,
'orphanRemoval' => false,
'redundantFields' => ['name'],
), $classMetadata->fieldMappings['groups']);

$this->assertEquals(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,17 @@
<cascade>
<all />
</cascade>
<redundant-fields>
<field name="name"/>
</redundant-fields>
</reference-many>
<reference-one target-document="Documents\Account" field="account">
<cascade>
<all />
</cascade>
<redundant-fields>
<field name="name"/>
</redundant-fields>
</reference-one>
<lifecycle-callbacks>
<lifecycle-callback method="doStuffOnPrePersist" type="prePersist" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,12 @@ TestDocuments\User:
account:
targetDocument: Documents\Account
cascade: all
redundantFields: [name]
referenceMany:
groups:
targetDocument: Documents\Group
cascade: all
redundantFields: [name]
lifecycleCallbacks:
prePersist: [doStuffOnPrePersist]
postPersist: [doStuffOnPostPersist, doOtherStuffOnPostPersist]
Expand Down