Skip to content

Commit

Permalink
Don't run update query if there is nothing to update
Browse files Browse the repository at this point in the history
  • Loading branch information
Ravan Scafi committed Dec 12, 2019
1 parent 485707b commit 7d1cc25
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/Mongolid/DataMapper/DataMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,10 @@ public function update($entity, array $options = []): bool
}

$data = $this->parseToDocument($entity);
$updateData = $this->getUpdateData($entity, $data);

if (!$updateData = $this->getUpdateData($entity, $data)) {
return true;
}

$queryResult = $this->getCollection()->updateOne(
['_id' => $data['_id']],
Expand Down
43 changes: 43 additions & 0 deletions tests/Mongolid/DataMapper/DataMapperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,49 @@ public function testDifferentialUpdateShouldWork()
$this->assertTrue($mapper->update($entity, $options));
}

public function testDifferentialUpdateShouldReturnTrueIfThereIsNothingToUpdate()
{
// Arrange
$entity = m::mock(AttributesAccessInterface::class);
$connPool = m::mock(Pool::class);
$mapper = m::mock(DataMapper::class.'[parseToDocument,getCollection]', [$connPool]);

$options = ['writeConcern' => new WriteConcern(1)];

$entity->_id = 123;
$parsedObject = [
'_id' => 123,
'name' => 'Original Name',
'age' => 32,
'hobbies' => ['bike', 'skate'],
'nested' => [['field' => null]],
'data' => ['key' => '123'],
];
$originalAttributes = $parsedObject;

// Act
$mapper->shouldAllowMockingProtectedMethods();

$mapper->shouldReceive('parseToDocument')
->once()
->with($entity)
->andReturn($parsedObject);

$mapper->shouldReceive('getCollection')
->never();

$entity->shouldReceive('originalAttributes')
->once()
->with()
->andReturn($originalAttributes);

$this->expectEventToBeFired('updating', $entity, true);
$this->expectEventNotToBeFired('updated', $entity);

// Assert
$this->assertTrue($mapper->update($entity, $options));
}

/**
* @dataProvider getWriteConcernVariations
*/
Expand Down

0 comments on commit 7d1cc25

Please sign in to comment.