-
Notifications
You must be signed in to change notification settings - Fork 823
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
NEW Add exists as a method to the DataQuery API that will generate an…
… SQL "exists" query The exists query in SQL allows the query optimiser (engine specific) to execute these queries much faster - often only needing the presence of an index to return "yes it exists".
- Loading branch information
Showing
2 changed files
with
30 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -453,6 +453,35 @@ public function count() | |
return $this->getFinalisedQuery()->count("DISTINCT {$quotedColumn}"); | ||
} | ||
|
||
/** | ||
* Return whether this dataquery will have records. This will use `EXISTS` statements in SQL which are more | ||
* performant - especially when used in combination with indexed columns (that you're filtering on) | ||
* | ||
* @return bool | ||
*/ | ||
public function exists() | ||
{ | ||
// Grab a statement selecting "everything" - the engine shouldn't care what's being selected in an "EXISTS" | ||
// statement anyway | ||
$statement = $this->getFinalisedQuery(); | ||
$statement->setSelect('*'); | ||
|
||
// Clear limit, distinct, grouping, and order as it's not relevant for an exists query | ||
$statement->setDistinct(false); | ||
$statement->setOrderBy(null); | ||
$statement->setGroupBy(null); | ||
$statement->setLimit(null); | ||
|
||
// Wrap the whole thing in an "EXISTS" | ||
$sql = 'SELECT EXISTS(' . $statement->sql($params) . ')'; | ||
$result = DB::prepared_query($sql, $params); | ||
$row = $result->first(); | ||
$result = reset($row); | ||
|
||
// Checking for 't' supports PostgreSQL before silverstripe/[email protected] | ||
return $result === 1 || $result === 't'; | ||
} | ||
|
||
/** | ||
* Return the maximum value of the given field in this DataList | ||
* | ||
|