Skip to content

Commit

Permalink
Fix database prune, offset not working on some dbs (#948)
Browse files Browse the repository at this point in the history
* Use left join to optimize prune query, and avoid using offset
  • Loading branch information
erikn69 committed Jun 26, 2024
1 parent 22682dd commit 28ecd2d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
17 changes: 15 additions & 2 deletions src/Drivers/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,22 @@ public function audit(Auditable $model): ?Audit
public function prune(Auditable $model): bool
{
if (($threshold = $model->getAuditThreshold()) > 0) {
$auditClass = get_class($model->audits()->getModel());
$auditModel = new $auditClass;

return $model->audits()
->latest()
->offset($threshold)->limit(PHP_INT_MAX)
->leftJoinSub(
$model->audits()->select($auditModel->getKeyName())->limit($threshold)->latest(),
'audit_threshold',
function ($join) use ($auditModel) {
$join->on(
$auditModel->gettable().'.'.$auditModel->getKeyName(),
'=',
'audit_threshold.'.$auditModel->getKeyName()
);
}
)
->whereNull('audit_threshold.'.$auditModel->getKeyName())
->delete() > 0;
}

Expand Down
15 changes: 11 additions & 4 deletions tests/Functional/AuditingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -297,16 +297,23 @@ public function itWillRemoveOlderAuditsAboveTheThreshold()
]);

$article = factory(Article::class)->create([
'reviewed' => 1,
'title' => 'Title #0',
]);

foreach (range(0, 99) as $count) {
foreach (range(1, 20) as $count) {
if ($count === 11) {
sleep(1);
}

$article->update([
'reviewed' => ($count % 2),
'title' => 'Title #' . $count,
]);
}

$this->assertSame(10, $article->audits()->count());
$audits = $article->audits()->get();
$this->assertSame(10, $audits->count());
$this->assertSame('Title #11', $audits->first()->new_values['title']);
$this->assertSame('Title #20', $audits->last()->new_values['title']);
}

/**
Expand Down

0 comments on commit 28ecd2d

Please sign in to comment.