[DB][Attachments] Use count function rathar than fetch and count, rename to refCount, rather than countDepencies

This commit is contained in:
Hugo Sales 2021-08-10 08:04:03 +00:00
parent 8880405dee
commit 39006fb6b5
Signed by: someonewithpc
GPG Key ID: 7D0C7EAFC9D835A0
3 changed files with 8 additions and 15 deletions

View File

@ -75,10 +75,9 @@ class Avatar extends Component
return Event::next; return Event::next;
} }
public function onAttachmentCountDependencies(int $attachment_id, int &$dependencies): bool public function onAttachmentRefCount(int $attachment_id, int &$dependencies): bool
{ {
$avatars = DB::findBy('avatar', ['attachment_id' => $attachment_id]); $dependencies += DB::count('avatar', ['attachment_id' => $attachment_id]);
$dependencies += count($avatars);
return Event::next; return Event::next;
} }

View File

@ -133,7 +133,7 @@ class Avatar extends Entity
if ($cascade) { if ($cascade) {
$attachment = $this->getAttachment(); $attachment = $this->getAttachment();
// We can't use $attachment->isSafeDelete() because underlying findBy doesn't respect remove persistence // We can't use $attachment->isSafeDelete() because underlying findBy doesn't respect remove persistence
if ($attachment->countDependencies() - 1 === 0) { if ($attachment->refCount() - 1 === 0) {
$attachment->delete(cascade: true, flush: false); $attachment->delete(cascade: true, flush: false);
} }
} }

View File

@ -246,28 +246,22 @@ class Attachment extends Entity
const URLHASH_ALGO = 'sha256'; const URLHASH_ALGO = 'sha256';
const FILEHASH_ALGO = 'sha256'; const FILEHASH_ALGO = 'sha256';
/** public function refCount(): int
*
* Warning: Underlying DB::findBy doesn't respect remove persistence
* @return int
*/
public function countDependencies(): int
{ {
$attachment_id = $this->getId(); $attachment_id = $this->getId();
$notes = DB::findBy('attachment_to_note', ['attachment_id' => $attachment_id]); $dependencies = DB::count('attachment_to_note', ['attachment_id' => $attachment_id]);
$dependencies = count($notes); Event::handle('AttachmentRefCount', [$attachment_id, &$dependencies]);
Event::handle('AttachmentCountDependencies', [$attachment_id, &$dependencies]);
return $dependencies; return $dependencies;
} }
/** /**
* @depends Attachment->refCount()
* *
* @depends Attachment->countDependencies()
* @return bool * @return bool
*/ */
public function isSafeDelete(): bool public function isSafeDelete(): bool
{ {
return $this->countDependencies() === 0; return $this->refCount() === 0;
} }
/** /**