Skip to content

Commit

Permalink
Add prefix check to index generation.
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonathan Gaillard committed Feb 5, 2014
1 parent ac11a16 commit d4bf1cd
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/DominionEnterprises/Mongo/Queue.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ public function ensureGetIndex(array $beforeSort = array(), array $afterSort = a

/**
* Ensure an index for the count() method.
* Is a no-op if the generated index is a prefix of an existing one. If you have a similar ensureGetIndex call, call it first.
*
* @param array $fields fields in count() call to index in same format as \MongoCollection::ensureIndex()
* @param bool $includeRunning whether to include the running field in the index
Expand Down Expand Up @@ -425,6 +426,7 @@ public function send(array $payload, $earliestGet = 0, $priority = 0.0)

/**
* Ensure index of correct specification and a unique name whether the specification or name already exist or not.
* Will not create index if $index is a prefix of an existing index
*
* @param array $index index to create in same format as \MongoCollection::ensureIndex()
*
Expand All @@ -434,6 +436,14 @@ public function send(array $payload, $earliestGet = 0, $priority = 0.0)
*/
private function _ensureIndex(array $index)
{
//if $index is a prefix of any existing index we are good
foreach ($this->_collection->getIndexInfo() as $existingIndex) {
$slice = array_slice($existingIndex['key'], 0, count($index), true);
if ($slice === $index) {
return;
}
}

for ($i = 0; $i < 5; ++$i) {
for ($name = uniqid(); strlen($name) > 0; $name = substr($name, 0, -1)) {
//creating an index with same name and different spec does nothing.
Expand Down
15 changes: 15 additions & 0 deletions tests/DominionEnterprises/Mongo/QueueTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,21 @@ public function ensureCountIndex()
$this->assertSame($expectedTwo, $resultTwo[2]['key']);
}

/**
* @test
*/
public function ensureCountIndexWithPrefixOfPrevious()
{
$this->_queue->ensureCountIndex(array('type' => 1, 'boo' => -1), false);
$this->_queue->ensureCountIndex(array('type' => 1), false);

$this->assertSame(2, count($this->_collection->getIndexInfo()));

$expected = array('payload.type' => 1, 'payload.boo' => -1);
$result = $this->_collection->getIndexInfo();
$this->assertSame($expected, $result[1]['key']);
}

/**
* @test
* @expectedException \InvalidArgumentException
Expand Down

0 comments on commit d4bf1cd

Please sign in to comment.