Passed
Push — dependabot/npm_and_yarn/nanoid... ( aaf2c9...c4aa90 )
by
unknown
14:37 queued 06:22
created

Version20241230175100   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 56
rs 10
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getForeignKeyName() 0 16 2
A up() 0 11 2
A getDescription() 0 3 1
A down() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Migrations\Schema\V200;
8
9
use Chamilo\CoreBundle\Migrations\AbstractMigrationChamilo;
10
use Doctrine\DBAL\Schema\Schema;
11
12
final class Version20241230175100 extends AbstractMigrationChamilo
13
{
14
    public function getDescription(): string
15
    {
16
        return 'Fix cascading delete for c_lp_category_rel_user table foreign key dynamically';
17
    }
18
19
    public function up(Schema $schema): void
20
    {
21
        // Find the foreign key name dynamically
22
        $foreignKeyName = $this->getForeignKeyName('c_lp_category_rel_user', 'user_id');
23
24
        if ($foreignKeyName) {
25
            $this->addSql("ALTER TABLE c_lp_category_rel_user DROP FOREIGN KEY `$foreignKeyName`");
26
        }
27
28
        // Add the updated foreign key
29
        $this->addSql('
30
            ALTER TABLE c_lp_category_rel_user
31
            ADD CONSTRAINT FK_83D35829A76ED395
32
            FOREIGN KEY (user_id)
33
            REFERENCES user(id)
34
            ON DELETE SET NULL
35
            ON UPDATE CASCADE
36
        ');
37
    }
38
39
    public function down(Schema $schema): void
40
    {
41
        $this->addSql('ALTER TABLE c_lp_category_rel_user DROP FOREIGN KEY FK_83D35829A76ED395');
42
43
        $this->addSql('
44
            ALTER TABLE c_lp_category_rel_user
45
            ADD CONSTRAINT c_lp_category_rel_user_ibfk_1
46
            FOREIGN KEY (user_id)
47
            REFERENCES user(id)
48
            ON DELETE SET NULL
49
        ');
50
    }
51
52
    private function getForeignKeyName(string $tableName, string $columnName): ?string
53
    {
54
        $query = '
55
            SELECT CONSTRAINT_NAME
56
            FROM information_schema.KEY_COLUMN_USAGE
57
            WHERE TABLE_NAME = :tableName
58
            AND COLUMN_NAME = :columnName
59
            AND TABLE_SCHEMA = DATABASE()
60
        ';
61
62
        $result = $this->connection->fetchOne($query, [
63
            'tableName' => $tableName,
64
            'columnName' => $columnName,
65
        ]);
66
67
        return $result ?: null;
68
    }
69
}
70