From d6dd10be9ca3cf184d12263bc230ef61dda661ad Mon Sep 17 00:00:00 2001 From: Mike Colagrosso Date: Mon, 23 Dec 2024 20:55:20 -0700 Subject: [PATCH] Clean up unused Tags, LocSubjects, and Collections On `Ebook::Save()` and `Ebook::Delete()`, remove any unreferenced `Tag`, `LocSubject`, and `Collection` records. These are analogous to these lines in `Ebook::Create()`: ``` $this->CreateTags(); $this->CreateLocSubjects(); $this->CreateCollections(); ``` `EbookPlaceholder`s can't have `Tags` or `LocSubjects` at the moment, but other mistakes in production that are later corrected could leave unused `Tags` and `LocSubjects`. Context: https://github.com/standardebooks/web/pull/447#issuecomment-2555734692 --- lib/Collection.php | 11 +++++++++++ lib/Ebook.php | 8 ++++++++ lib/EbookTag.php | 13 +++++++++++++ lib/LocSubject.php | 12 ++++++++++++ 4 files changed, 44 insertions(+) diff --git a/lib/Collection.php b/lib/Collection.php index 6360cee9..9763d4ac 100644 --- a/lib/Collection.php +++ b/lib/Collection.php @@ -99,6 +99,17 @@ class Collection{ ', [], Collection::class); } + /** + * Deletes `Collection`s that no `Ebook`s are members of. + */ + public static function DeleteUnused(): void{ + Db::Query(' + DELETE + from Collections + where CollectionId not in + (select distinct CollectionId from CollectionEbooks) + '); + } // ******* // METHODS diff --git a/lib/Ebook.php b/lib/Ebook.php index 424fb780..3d0d4f7c 100644 --- a/lib/Ebook.php +++ b/lib/Ebook.php @@ -1984,6 +1984,10 @@ final class Ebook{ $this->RemoveEbookPlaceholder(); $this->AddEbookPlaceholder(); + + EbookTag::DeleteUnused(); + LocSubject::DeleteUnused(); + Collection::DeleteUnused(); } catch(Exceptions\ValidationException $ex){ $error = new Exceptions\InvalidEbookException(); @@ -2176,6 +2180,10 @@ final class Ebook{ $this->RemoveTocEntries(); $this->RemoveEbookPlaceholder(); + EbookTag::DeleteUnused(); + LocSubject::DeleteUnused(); + Collection::DeleteUnused(); + foreach($this->Projects as $project){ $project->Delete(); } diff --git a/lib/EbookTag.php b/lib/EbookTag.php index e56f6ef1..bfa6fcaf 100644 --- a/lib/EbookTag.php +++ b/lib/EbookTag.php @@ -107,4 +107,17 @@ class EbookTag extends Tag{ return $tags; } + + /** + * Deletes `EbookTag`s that are not associated with any `Ebook`s. + */ + public static function DeleteUnused(): void{ + Db::Query(' + DELETE + from Tags + where Type = ? + and TagId not in + (select distinct TagId from EbookTags) + ', [Enums\TagType::Ebook]); + } } diff --git a/lib/LocSubject.php b/lib/LocSubject.php index 040bffe9..880fb3a1 100644 --- a/lib/LocSubject.php +++ b/lib/LocSubject.php @@ -64,4 +64,16 @@ class LocSubject{ return $this; } } + + /** + * Deletes `LocSubject`s that are not associated with any `Ebook`s. + */ + public static function DeleteUnused(): void{ + Db::Query(' + DELETE + from LocSubjects + where LocSubjectId not in + (select distinct LocSubjectId from EbookLocSubjects) + '); + } }