Skip to content

Add hasIndex and dropIndexIfExists methods #1790

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

Merged
merged 4 commits into from
Oct 3, 2019
Merged
Changes from 2 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
60 changes: 49 additions & 11 deletions src/Jenssegers/Mongodb/Schema/Blueprint.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,21 +78,24 @@ public function primary($columns = null, $name = null, $algorithm = null, $optio
*/
public function dropIndex($indexOrColumns = null)
{
if (is_array($indexOrColumns)) {
$indexOrColumns = $this->fluent($indexOrColumns);
$indexOrColumns = $this->transformColumns($indexOrColumns);

// Transform the columns to the index name.
$transform = [];
$this->collection->dropIndex($indexOrColumns);

foreach ($indexOrColumns as $column) {
$transform[$column] = $column . '_1';
}
return $this;
}

$indexOrColumns = join('_', $transform);
/**
* Indicate that the given index should be dropped, but do not fail if it didn't exist.
*
* @param string|array $indexOrColumns
* @return Blueprint
*/
public function dropIndexIfExists($indexOrColumns = null)
{
if ($this->hasIndex($indexOrColumns)) {
$this->dropIndex($indexOrColumns);
}

$this->collection->dropIndex($indexOrColumns);

return $this;
}

Expand Down Expand Up @@ -235,6 +238,41 @@ public function sparse_and_unique($columns = null, $options = [])
return $this;
}

/**
* Check whether the given index exists.
*
* @param string|array $indexOrColumns
* @return bool
*/
public function hasIndex($indexOrColumns = null)
{
$indexOrColumns = $this->transformColumns($indexOrColumns);
foreach ($this->collection->listIndexes() as $index) {
if ($index->getName() == $indexOrColumns) {
return true;
}
}
return false;
}

/**
* @param string|array $indexOrColumns
* @return string|array
*/
private function transformColumns($indexOrColumns)
{
if (is_array($indexOrColumns)) {
$indexOrColumns = $this->fluent($indexOrColumns);
// Transform the columns to the index name.
$transform = [];
foreach ($indexOrColumns as $column) {
$transform[$column] = $column . '_1';
}
$indexOrColumns = join('_', $transform);
}
return $indexOrColumns;
}

/**
* Allow fluent columns.
*
Expand Down