-
Notifications
You must be signed in to change notification settings - Fork 642
/
Copy pathGc.php
805 lines (699 loc) · 26 KB
/
Gc.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\services;
use Craft;
use craft\base\ElementInterface;
use craft\base\NestedElementInterface;
use craft\config\GeneralConfig;
use craft\console\Application as ConsoleApplication;
use craft\db\Connection;
use craft\db\Query;
use craft\db\Table;
use craft\elements\Address;
use craft\elements\Asset;
use craft\elements\Category;
use craft\elements\Entry;
use craft\elements\GlobalSet;
use craft\elements\Tag;
use craft\elements\User;
use craft\errors\FsException;
use craft\fs\Temp;
use craft\helpers\Console;
use craft\helpers\DateTimeHelper;
use craft\helpers\Db;
use craft\records\Volume;
use craft\records\VolumeFolder;
use DateTime;
use ReflectionMethod;
use yii\base\Component;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\di\Instance;
/**
* Garbage Collection service.
*
* An instance of the service is available via [[\craft\base\ApplicationTrait::getGc()|`Craft::$app->gc`]].
*
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 3.1.0
*/
class Gc extends Component
{
/**
* @event Event The event that is triggered when running garbage collection.
*/
public const EVENT_RUN = 'run';
/**
* @var int the probability (parts per million) that garbage collection (GC) should be performed
* on a request. Defaults to 10, meaning 0.001% chance.
*
* This number should be between 0 and 1000000. A value 0 means no GC will be performed at all unless forced.
*/
public int $probability = 10;
/**
* @var bool whether [[hardDelete()]] should delete *all* soft-deleted rows,
* rather than just the ones that were deleted long enough ago to be ready
* for hard-deletion per the <config5:softDeleteDuration> config setting.
*/
public bool $deleteAllTrashed = false;
/**
* @var Connection|array|string The database connection to use
* @since 4.0.0
*/
public string|array|Connection $db = 'db';
/**
* @var GeneralConfig
*/
private GeneralConfig $_generalConfig;
/**
* @inheritdoc
*/
public function init()
{
$this->db = Instance::ensure($this->db, Connection::class);
$this->_generalConfig = Craft::$app->getConfig()->getGeneral();
parent::init();
}
/**
* Possibly runs garbage collection.
*
* @param bool $force Whether garbage collection should be forced. If left as `false`, then
* garbage collection will only run if a random condition passes, factoring in [[probability]].
*/
public function run(bool $force = false): void
{
if (!$force && mt_rand(0, 1000000) >= $this->probability) {
return;
}
$this->_purgeUnsavedDrafts();
$this->_purgePendingUsers();
$this->_deleteStaleSessions();
$this->_deleteStaleAnnouncements();
$this->_deleteStaleElementActivity();
$this->_deleteStaleBulkElementOps();
// elements should always go first
$this->hardDeleteElements();
$this->hardDelete([
Table::CATEGORYGROUPS,
Table::ENTRYTYPES,
Table::FIELDS,
Table::SECTIONS,
Table::TAGGROUPS,
]);
$this->deletePartialElements(Address::class, Table::ADDRESSES, 'id');
$this->deletePartialElements(Asset::class, Table::ASSETS, 'id');
$this->deletePartialElements(Category::class, Table::CATEGORIES, 'id');
$this->deletePartialElements(Entry::class, Table::ENTRIES, 'id');
$this->deletePartialElements(GlobalSet::class, Table::GLOBALSETS, 'id');
$this->deletePartialElements(Tag::class, Table::TAGS, 'id');
$this->deletePartialElements(User::class, Table::USERS, 'id');
$this->_deleteUnsupportedSiteEntries();
$this->deleteOrphanedNestedElements(Address::class, Table::ADDRESSES);
$this->deleteOrphanedNestedElements(Entry::class, Table::ENTRIES);
// Fire a 'run' event
// Note this should get fired *before* orphaned drafts & revisions are deleted
// (see https://github.com/craftcms/cms/issues/14309)
if ($this->hasEventHandlers(self::EVENT_RUN)) {
$this->trigger(self::EVENT_RUN);
}
$this->_deleteOrphanedDraftsAndRevisions();
$this->_deleteOrphanedSearchIndexes();
$this->_deleteOrphanedRelations();
$this->_deleteOrphanedStructureElements();
$this->_hardDeleteStructures();
$this->hardDelete([
Table::FIELDLAYOUTS,
Table::SITES,
]);
$this->hardDeleteVolumes();
$this->removeEmptyTempFolders();
$this->_gcCache();
// Invalidate all element caches so any hard-deleted elements don't look like they still exist
Craft::$app->getElements()->invalidateAllCaches();
}
/**
* Hard delete eligible volumes, deleting the folders one by one to avoid nested dependency errors.
*/
public function hardDeleteVolumes(): void
{
if (!$this->_shouldHardDelete()) {
return;
}
$this->_stdout(" > deleting trashed volumes and their folders ... ");
$condition = $this->_hardDeleteCondition();
$volumes = (new Query())->select(['id'])->from([Table::VOLUMES])->where($condition)->all();
$volumeIds = [];
foreach ($volumes as $volume) {
$volumeIds[] = $volume['id'];
}
$folders = (new Query())->select(['id', 'path'])->from([Table::VOLUMEFOLDERS])->where(['volumeId' => $volumeIds])->all();
usort($folders, function($a, $b) {
return substr_count($a['path'], '/') < substr_count($b['path'], '/');
});
foreach ($folders as $folder) {
VolumeFolder::deleteAll(['id' => $folder['id']]);
}
Volume::deleteAll(['id' => $volumeIds]);
$this->_stdout("done\n", Console::FG_GREEN);
}
/**
* Hard-deletes eligible elements.
*
* Any soft-deleted nested elements which have revisions will be skipped, as their revisions may still be needed by the owner element.
*
* @since 4.0.0
*/
public function hardDeleteElements(): void
{
if (!$this->_shouldHardDelete()) {
return;
}
$normalElementTypes = [];
$nestedElementTypes = [];
foreach (Craft::$app->getElements()->getAllElementTypes() as $elementType) {
if (is_subclass_of($elementType, NestedElementInterface::class)) {
$nestedElementTypes[] = $elementType;
} else {
$normalElementTypes[] = $elementType;
}
}
$this->_stdout(' > deleting trashed elements ... ');
if ($normalElementTypes) {
Db::delete(Table::ELEMENTS, [
'and',
$this->_hardDeleteCondition(),
['type' => $normalElementTypes],
]);
}
if (!empty($nestedElementTypes)) {
$elementsTable = Table::ELEMENTS;
$revisionsTable = Table::REVISIONS;
$elementsOwnersTable = Table::ELEMENTS_OWNERS;
// first hard-delete nested elements which are not nested (owned) and that don't have any revisions
$params = [];
$conditionSql = $this->db->getQueryBuilder()->buildCondition([
'and',
$this->_hardDeleteCondition('e'),
[
'e.type' => $nestedElementTypes,
'r.id' => null,
'eo.elementId' => null,
],
], $params);
if ($this->db->getIsMysql()) {
$sql = <<<SQL
DELETE [[e]].* FROM $elementsTable [[e]]
LEFT JOIN $revisionsTable [[r]] ON [[r.canonicalId]] = [[e.id]]
LEFT JOIN $elementsOwnersTable [[eo]] ON [[eo.elementId]] = COALESCE([[e.canonicalId]], [[e.id]])
WHERE $conditionSql
SQL;
} else {
$sql = <<<SQL
DELETE FROM $elementsTable
USING $elementsTable [[e]]
LEFT JOIN $revisionsTable [[r]] ON [[r.canonicalId]] = [[e.id]]
LEFT JOIN $elementsOwnersTable [[eo]] ON [[eo.elementId]] = COALESCE([[e.canonicalId]], [[e.id]])
WHERE
$elementsTable.[[id]] = [[e.id]] AND $conditionSql
SQL;
}
$this->db->createCommand($sql, $params)->execute();
// then hard-delete any nested elements that don't have any revisions, including nested ones
$params = [];
$conditionSql = $this->db->getQueryBuilder()->buildCondition([
'and',
$this->_hardDeleteCondition('e'),
[
'e.type' => $nestedElementTypes,
'r.id' => null,
],
], $params);
if ($this->db->getIsMysql()) {
$sql = <<<SQL
DELETE [[e]].* FROM $elementsTable [[e]]
LEFT JOIN $revisionsTable [[r]] ON [[r.canonicalId]] = COALESCE([[e.canonicalId]], [[e.id]])
WHERE $conditionSql
SQL;
} else {
$sql = <<<SQL
DELETE FROM $elementsTable
USING $elementsTable [[e]]
LEFT JOIN $revisionsTable [[r]] ON [[r.canonicalId]] = COALESCE([[e.canonicalId]], [[e.id]])
WHERE
$elementsTable.[[id]] = [[e.id]] AND $conditionSql
SQL;
}
$this->db->createCommand($sql, $params)->execute();
}
$this->_stdout("done\n", Console::FG_GREEN);
}
/**
* Hard-deletes any rows in the given table(s), that are due for it.
*
* @param string|string[] $tables The table(s) to delete rows from. They must have a `dateDeleted` column.
*/
public function hardDelete(array|string $tables): void
{
if (!$this->_shouldHardDelete()) {
return;
}
$condition = $this->_hardDeleteCondition();
if (!is_array($tables)) {
$tables = [$tables];
}
foreach ($tables as $table) {
$this->_stdout(" > deleting trashed rows in the `$table` table ... ");
Db::delete($table, $condition);
$this->_stdout("done\n", Console::FG_GREEN);
}
}
/**
* Deletes elements that are missing data in the given element extension table.
*
* @param string $elementType The element type
* @phpstan-param class-string<ElementInterface> $elementType
* @param string $table The extension table name
* @param string $fk The column name that contains the foreign key to `elements.id`
* @since 3.6.6
*/
public function deletePartialElements(string $elementType, string $table, string $fk): void
{
/** @var string|ElementInterface $elementType */
$this->_stdout(sprintf(' > deleting partial %s data in the `%s` table ... ', $elementType::lowerDisplayName(), $table));
$elementsTable = Table::ELEMENTS;
if ($this->db->getIsMysql()) {
$sql = <<<SQL
DELETE [[e]].* FROM $elementsTable [[e]]
LEFT JOIN $table [[t]] ON [[t.$fk]] = [[e.id]]
WHERE
[[e.type]] = :type AND
[[t.$fk]] IS NULL
SQL;
} else {
$sql = <<<SQL
DELETE FROM $elementsTable
USING $elementsTable [[e]]
LEFT JOIN $table [[t]] ON [[t.$fk]] = [[e.id]]
WHERE
$elementsTable.[[id]] = [[e.id]] AND
[[e.type]] = :type AND
[[t.$fk]] IS NULL
SQL;
}
$this->db->createCommand($sql, ['type' => $elementType])->execute();
$this->_stdout("done\n", Console::FG_GREEN);
}
private function _purgeUnsavedDrafts()
{
if ($this->_generalConfig->purgeUnsavedDraftsDuration === 0) {
return;
}
$this->_stdout(' > purging unsaved drafts that have gone stale ... ');
Craft::$app->getDrafts()->purgeUnsavedDrafts();
$this->_stdout("done\n", Console::FG_GREEN);
}
private function _purgePendingUsers()
{
if ($this->_generalConfig->purgePendingUsersDuration === 0) {
return;
}
$this->_stdout(' > purging pending users with stale activation codes ... ');
Craft::$app->getUsers()->purgeExpiredPendingUsers();
$this->_stdout("done\n", Console::FG_GREEN);
}
/**
* Find all temp upload folders with no assets in them and remove them.
*
* @throws FsException
* @throws Exception
* @throws InvalidConfigException
* @since 4.0.0
*/
public function removeEmptyTempFolders(): void
{
$this->_stdout(' > removing empty temp folders ... ');
$emptyFolders = (new Query())
->select(['folders.id', 'folders.path'])
->from(['folders' => Table::VOLUMEFOLDERS])
->leftJoin(['assets' => Table::ASSETS], '[[assets.folderId]] = [[folders.id]]')
->where([
'folders.volumeId' => null,
'assets.id' => null,
])
->andWhere(['not', ['folders.parentId' => null]])
->andWhere(['not', ['folders.path' => null]])
->pairs();
$fs = Craft::createObject(Temp::class);
foreach ($emptyFolders as $emptyFolderPath) {
if ($fs->directoryExists($emptyFolderPath)) {
$fs->deleteDirectory($emptyFolderPath);
}
}
VolumeFolder::deleteAll(['id' => array_keys($emptyFolders)]);
$this->_stdout("done\n", Console::FG_GREEN);
}
/**
* Returns whether we should be hard-deleting soft-deleted objects.
*
* @return bool
*/
private function _shouldHardDelete(): bool
{
return $this->_generalConfig->softDeleteDuration || $this->deleteAllTrashed;
}
/**
* Deletes any session rows that have gone stale.
*/
private function _deleteStaleSessions(): void
{
if ($this->_generalConfig->purgeStaleUserSessionDuration === 0) {
return;
}
$this->_stdout(' > deleting stale user sessions ... ');
$interval = DateTimeHelper::secondsToInterval($this->_generalConfig->purgeStaleUserSessionDuration);
$expire = DateTimeHelper::currentUTCDateTime();
$pastTime = $expire->sub($interval);
Db::delete(Table::SESSIONS, ['<', 'dateUpdated', Db::prepareDateForDb($pastTime)]);
$this->_stdout("done\n", Console::FG_GREEN);
}
/**
* Deletes any feature announcement rows that have gone stale.
*/
private function _deleteStaleAnnouncements(): void
{
$this->_stdout(' > deleting stale feature announcements ... ');
Db::delete(Table::ANNOUNCEMENTS, ['<', 'dateRead', Db::prepareDateForDb(new DateTime('7 days ago'))]);
$this->_stdout("done\n", Console::FG_GREEN);
}
/**
* Deletes any stale element activity logs.
*/
private function _deleteStaleElementActivity(): void
{
$this->_stdout(' > deleting stale element activity records ... ');
Db::delete(Table::ELEMENTACTIVITY, ['<', 'timestamp', Db::prepareDateForDb(new DateTime('1 minute ago'))]);
$this->_stdout("done\n", Console::FG_GREEN);
}
/**
* Deletes any stale bulk element operation records.
*/
private function _deleteStaleBulkElementOps(): void
{
$this->_stdout(' > deleting stale bulk element operation records ... ');
Db::delete(Table::ELEMENTS_BULKOPS, ['<', 'timestamp', Db::prepareDateForDb(new DateTime('2 weeks ago'))]);
$this->_stdout("done\n", Console::FG_GREEN);
}
/**
* Deletes entries for sites that aren’t enabled by their section.
*
* This can happen if you entrify a category group, disable one of the sites in the newly-created section’s
* settings, then deploy those changes to another environment, apply project config changes, and re-run the
* entrify command. (https://github.com/craftcms/cms/issues/13383)
*/
private function _deleteUnsupportedSiteEntries(): void
{
$this->_stdout(' > deleting entries in unsupported sites ... ');
$sectionsToCheck = [];
$siteIds = Craft::$app->getSites()->getAllSiteIds(true);
// get sections that are not enabled for given site
foreach (Craft::$app->getEntries()->getAllSections() as $section) {
$sectionSettings = $section->getSiteSettings();
foreach ($siteIds as $siteId) {
if (!isset($sectionSettings[$siteId])) {
$sectionsToCheck[] = [
'siteId' => $siteId,
'sectionId' => $section->id,
];
}
}
}
if (!empty($sectionsToCheck)) {
$elementsSitesTable = Table::ELEMENTS_SITES;
$entriesTable = Table::ENTRIES;
if ($this->db->getIsMysql()) {
$sql = <<<SQL
DELETE [[es]].* FROM $elementsSitesTable [[es]]
LEFT JOIN $entriesTable [[en]] ON [[en.id]] = [[es.elementId]]
WHERE [[en.sectionId]] = :sectionId AND [[es.siteId]] = :siteId
SQL;
} else {
$sql = <<<SQL
DELETE FROM $elementsSitesTable
USING $elementsSitesTable [[es]]
LEFT JOIN $entriesTable [[en]] ON [[en.id]] = [[es.elementId]]
WHERE
$elementsSitesTable.[[id]] = [[es.id]] AND
[[en.sectionId]] = :sectionId AND [[es.siteId]] = :siteId
SQL;
}
foreach ($sectionsToCheck as $params) {
$this->db->createCommand($sql, $params)->execute();
}
}
$this->_stdout("done\n", Console::FG_GREEN);
}
/**
* Deletes elements which have a `fieldId` value, but it’s set to an invalid field ID,
* or they're missing a row in the `elements_owners` table.
*
* @param string $elementType The element type
* @phpstan-param class-string<ElementInterface> $elementType
* @param string $table The extension table name
* @param string $fieldFk The column name that contains the foreign key to `fields.id`
* @since 5.4.2
*/
public function deleteOrphanedNestedElements(string $elementType, string $table, string $fieldFk = 'fieldId'): void
{
/** @var string|ElementInterface $elementType */
$this->_stdout(sprintf(' > deleting orphaned nested %s ... ', $elementType::pluralLowerDisplayName()));
$elementsTable = Table::ELEMENTS;
$elementsOwnersTable = Table::ELEMENTS_OWNERS;
$fieldsTable = Table::FIELDS;
if ($this->db->getIsMysql()) {
$sql1 = <<<SQL
DELETE [[el]].* FROM $elementsTable [[el]]
INNER JOIN $table [[t]] ON [[t.id]] = [[el.id]]
LEFT JOIN $elementsOwnersTable [[eo]] ON [[eo.elementId]] = [[el.id]]
WHERE [[t.$fieldFk]] IS NOT NULL AND [[eo.elementId]] IS NULL
SQL;
$sql2 = <<<SQL
DELETE [[el]].* FROM $elementsTable [[el]]
INNER JOIN $table [[t]] ON [[t.id]] = [[el.id]]
LEFT JOIN $fieldsTable [[f]] ON [[f.id]] = [[t.$fieldFk]]
WHERE [[t.$fieldFk]] IS NOT NULL AND [[f.id]] IS NULL
SQL;
} else {
$sql1 = <<<SQL
DELETE FROM $elementsTable
USING $elementsTable [[el]]
INNER JOIN $table [[t]] ON [[t.id]] = [[el.id]]
LEFT JOIN $elementsOwnersTable [[eo]] ON [[eo.elementId]] = [[el.id]]
WHERE [[t.$fieldFk]] IS NOT NULL AND [[eo.elementId]] IS NULL
SQL;
$sql2 = <<<SQL
DELETE FROM $elementsTable
USING $elementsTable [[el]]
INNER JOIN $table [[t]] ON [[t.id]] = [[el.id]]
LEFT JOIN $fieldsTable [[f]] ON [[f.id]] = [[t.$fieldFk]]
WHERE [[t.$fieldFk]] IS NOT NULL AND [[f.id]] IS NULL
SQL;
}
$this->db->createCommand($sql1)->execute();
$this->db->createCommand($sql2)->execute();
$this->_stdout("done\n", Console::FG_GREEN);
}
/**
* Deletes any orphaned rows in the `drafts` and `revisions` tables.
*/
private function _deleteOrphanedDraftsAndRevisions(): void
{
$this->_stdout(' > deleting orphaned drafts and revisions ... ');
$elementsTable = Table::ELEMENTS;
foreach (['draftId' => Table::DRAFTS, 'revisionId' => Table::REVISIONS] as $fk => $table) {
if ($this->db->getIsMysql()) {
$sql = <<<SQL
DELETE [[t]].* FROM $table [[t]]
LEFT JOIN $elementsTable [[e]] ON [[e.$fk]] = [[t.id]]
WHERE [[e.id]] IS NULL
SQL;
} else {
$sql = <<<SQL
DELETE FROM $table
USING $table [[t]]
LEFT JOIN $elementsTable [[e]] ON [[e.$fk]] = [[t.id]]
WHERE
$table.[[id]] = [[t.id]] AND
[[e.id]] IS NULL
SQL;
}
$this->db->createCommand($sql)->execute();
}
$this->_stdout("done\n", Console::FG_GREEN);
}
private function _deleteOrphanedSearchIndexes(): void
{
$this->_stdout(' > deleting orphaned search indexes ... ');
Craft::$app->getSearch()->deleteOrphanedIndexes();
$this->_stdout("done\n", Console::FG_GREEN);
}
private function _deleteOrphanedRelations(): void
{
$this->_stdout(' > deleting orphaned relations ... ');
$relationsTable = Table::RELATIONS;
$elementsTable = Table::ELEMENTS;
if ($this->db->getIsMysql()) {
$sql = <<<SQL
DELETE [[r]].* FROM $relationsTable [[r]]
LEFT JOIN $elementsTable [[e]] ON [[e.id]] = [[r.targetId]]
WHERE [[e.id]] IS NULL
SQL;
} else {
$sql = <<<SQL
DELETE FROM $relationsTable
USING $relationsTable [[r]]
LEFT JOIN $elementsTable [[e]] ON [[e.id]] = [[r.targetId]]
WHERE
$relationsTable.[[id]] = [[r.id]] AND
[[e.id]] IS NULL
SQL;
}
$this->db->createCommand($sql)->execute();
$this->_stdout("done\n", Console::FG_GREEN);
}
private function _deleteOrphanedStructureElements(): void
{
$this->_stdout(' > deleting orphaned structure elements ... ');
$structureElementsTable = Table::STRUCTUREELEMENTS;
$elementsTable = Table::ELEMENTS;
if ($this->db->getIsMysql()) {
$sql = <<<SQL
DELETE [[se]].* FROM $structureElementsTable [[se]]
LEFT JOIN $elementsTable [[e]] ON [[e.id]] = [[se.elementId]]
WHERE [[se.elementId]] IS NOT NULL AND [[e.id]] IS NULL
SQL;
} else {
$sql = <<<SQL
DELETE FROM $structureElementsTable
USING $structureElementsTable [[se]]
LEFT JOIN $elementsTable [[e]] ON [[e.id]] = [[se.elementId]]
WHERE
$structureElementsTable.[[id]] = [[se.id]] AND
[[se.elementId]] IS NOT NULL AND
[[e.id]] IS NULL
SQL;
}
$this->db->createCommand($sql)->execute();
$this->_stdout("done\n", Console::FG_GREEN);
}
/**
* Hard delete structures data
* Any soft-deleted structure elements which have revisions will be skipped, as their revisions may still be needed by the owner element.
*
* @return void
* @throws \yii\db\Exception
*/
private function _hardDeleteStructures(): void
{
// get IDs of structures that can be deleted;
// those are the ones for which the elements don't have any revisions
$structuresTable = Table::STRUCTURES;
$structureElementsTable = Table::STRUCTUREELEMENTS;
$elementsTable = Table::ELEMENTS;
$revisionsTable = Table::REVISIONS;
$params = [];
$structureIds = (new Query())
->select('[[s.id]]')
->distinct()
->from(['s' => $structuresTable])
->leftJoin(['se' => $structureElementsTable], '[[s.id]] = [[se.structureId]]')
->leftJoin(['e' => $elementsTable], '[[e.id]] = [[se.elementId]]')
->leftJoin(['r' => $revisionsTable], '[[r.canonicalId]] = coalesce([[e.canonicalId]],[[e.id]])')
->where([
'and',
['not', ['se.elementId' => null]],
$this->_hardDeleteCondition('s'),
[
'r.canonicalId' => null,
],
])
->column();
if (!empty($structureIds)) {
$ids = implode(',', $structureIds);
$conditionSql = $this->db->getQueryBuilder()->buildCondition($this->_hardDeleteCondition('s'), $params);
// and now perform the actual deletion based on those IDs
if ($this->db->getIsMysql()) {
$sql = <<<SQL
DELETE [[s]].* FROM $structuresTable [[s]]
WHERE [[s.id]] IN ($ids)
AND $conditionSql
SQL;
} else {
$sql = <<<SQL
DELETE FROM $structuresTable
USING $structuresTable [[s]]
WHERE
$structuresTable.[[id]] = [[s.id]] AND
[[s.id]] IN ($ids) AND
$conditionSql
SQL;
}
$this->db->createCommand($sql, $params)->execute();
}
}
private function _gcCache(): void
{
$cache = Craft::$app->getCache();
// gc() isn't always implemented, or defined by an interface,
// so we have to be super defensive here :-/
if (!method_exists($cache, 'gc')) {
return;
}
$method = new ReflectionMethod($cache, 'gc');
if (!$method->isPublic()) {
return;
}
$requiredArgs = $method->getNumberOfRequiredParameters();
$firstArg = $method->getParameters()[0] ?? null;
$hasForceArg = $firstArg && $firstArg->getName() === 'force';
if ($requiredArgs > 1 || ($requiredArgs === 1 && !$hasForceArg)) {
return;
}
$this->_stdout(' > garbage-collecting data caches ... ');
if ($hasForceArg) {
$cache->gc(true);
} else {
$cache->gc();
}
$this->_stdout("done\n", Console::FG_GREEN);
}
/**
* @param string|null $tableAlias
* @return array
*/
private function _hardDeleteCondition(?string $tableAlias = null): array
{
$tableAlias = $tableAlias ? "$tableAlias." : '';
$condition = ['not', ["{$tableAlias}dateDeleted" => null]];
if (!$this->deleteAllTrashed) {
$expire = DateTimeHelper::currentUTCDateTime();
$interval = DateTimeHelper::secondsToInterval($this->_generalConfig->softDeleteDuration);
$pastTime = $expire->sub($interval);
$condition = [
'and',
$condition,
['<', "{$tableAlias}dateDeleted", Db::prepareDateForDb($pastTime)],
];
}
return $condition;
}
private function _stdout(string $string, ...$format): void
{
if (Craft::$app instanceof ConsoleApplication) {
Console::stdout($string, ...$format);
}
}
}