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

Improve performance on queries with skipAddTrashCondition. #71

Merged
merged 4 commits into from
Feb 3, 2025
Merged
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
29 changes: 23 additions & 6 deletions src/Model/Behavior/TrashBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,26 @@ public function trash(EntityInterface $entity, array $options = []): bool
*/
public function beforeFind(EventInterface $event, SelectQuery $query, ArrayObject $options, bool $primary): void
{
if (!empty($options['skipAddTrashCondition'])) {
return;
}

$field = $this->getTrashField();

if ($this->shouldAddTrashCondition($query, $field)) {
$query->andWhere([$field . ' IS' => null]);
}
}

/**
* Whether we need to add the trash condition to the query
*
* @param \Cake\ORM\Query\SelectQuery $query Query.
* @param string $field Trash field
* @return bool
*/
protected function shouldAddTrashCondition(SelectQuery $query, string $field): bool
{
$addCondition = true;

$query->traverseExpressions(function ($expression) use (&$addCondition, $field): void {
Expand All @@ -205,11 +224,7 @@ public function beforeFind(EventInterface $event, SelectQuery $query, ArrayObjec
}
});

$option = $query->getOptions();

if ($addCondition && empty($option['skipAddTrashCondition'])) {
$query->andWhere($query->newExpr()->isNull($field));
}
return $addCondition;
}

/**
Expand All @@ -221,7 +236,9 @@ public function beforeFind(EventInterface $event, SelectQuery $query, ArrayObjec
*/
public function findOnlyTrashed(SelectQuery $query, array $options): SelectQuery
{
return $query->andWhere($query->newExpr()->isNotNull($this->getTrashField()));
return $query
->applyOptions(['skipAddTrashCondition' => true])
->andWhere($query->newExpr()->isNotNull($this->getTrashField()));
}

/**
Expand Down