Skip to content

Commit

Permalink
add foreign key to addresses fieldId column + gc adjustment
Browse files Browse the repository at this point in the history
  • Loading branch information
i-just committed Sep 6, 2024
1 parent 5e90c47 commit 1d4e8fc
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/config/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
'id' => 'CraftCMS',
'name' => 'Craft CMS',
'version' => '5.4.1',
'schemaVersion' => '5.3.0.2',
'schemaVersion' => '5.3.0.3',
'minVersionRequired' => '4.5.0',
'basePath' => dirname(__DIR__), // Defines the @app alias
'runtimePath' => '@storage/runtime', // Defines the @runtime alias
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace craft\migrations;

use craft\db\Migration;
use craft\db\Table;

/**
* m240906_115231_add_addresses_fieldid_fk_constraint migration.
*/
class m240906_115231_add_addresses_fieldid_fk_constraint extends Migration
{
/**
* @inheritdoc
*/
public function safeUp(): bool
{
// first clean up addresses that already belong to fields that were hard deleted
$addressesTable = Table::ADDRESSES;
$fieldsTable = Table::FIELDS;

if ($this->db->getIsMysql()) {
$sql = <<<SQL
DELETE [[a]].* FROM $addressesTable [[a]]
LEFT JOIN $fieldsTable [[f]] ON [[f.id]] = [[a.fieldId]]
WHERE [[a.fieldId]] IS NOT NULL AND
[[f.id]] IS NULL
SQL;
} else {
$sql = <<<SQL
DELETE FROM $addressesTable
USING $addressesTable [[a]]
LEFT JOIN $fieldsTable [[f]] ON [[f.id]] = [[a.fieldId]]
WHERE
$addressesTable.[[id]] = [[a.id]] AND
[[a.fieldId]] IS NOT NULL AND
[[f.id]] IS NULL
SQL;
}

$this->db->createCommand($sql)->execute();

// and now add a foreign key
$this->addForeignKey(null, Table::ADDRESSES, ['fieldId'], Table::FIELDS, ['id'], 'CASCADE', null);

return true;
}

/**
* @inheritdoc
*/
public function safeDown(): bool
{
echo "m240906_115231_add_addresses_fieldid_fk_constraint cannot be reverted.\n";
return false;
}
}
2 changes: 2 additions & 0 deletions src/services/Gc.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
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;
Expand Down Expand Up @@ -115,6 +116,7 @@ public function run(bool $force = false): void
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');
Expand Down

0 comments on commit 1d4e8fc

Please sign in to comment.