RemoveNamespacedAssets.php 2.02 KB
Newer Older
1 2
<?php

Michael Moravec's avatar
Michael Moravec committed
3 4
declare(strict_types=1);

5 6
namespace Doctrine\DBAL\Schema\Visitor;

Benjamin Morel's avatar
Benjamin Morel committed
7
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
8
use Doctrine\DBAL\Schema\Schema;
Benjamin Morel's avatar
Benjamin Morel committed
9
use Doctrine\DBAL\Schema\Sequence;
10
use Doctrine\DBAL\Schema\Table;
11 12

/**
Benjamin Morel's avatar
Benjamin Morel committed
13
 * Removes assets from a schema that are not in the default namespace.
14 15 16 17 18 19 20 21 22
 *
 * Some databases such as MySQL support cross databases joins, but don't
 * allow to call DDLs to a database from another connected database.
 * Before a schema is serialized into SQL this visitor can cleanup schemas with
 * non default namespaces.
 *
 * This visitor filters all these non-default namespaced tables and sequences
 * and removes them from the SChema instance.
 */
23
final class RemoveNamespacedAssets extends AbstractVisitor
24
{
25
    /** @var Schema */
26 27
    private $schema;

28
    public function acceptSchema(Schema $schema) : void
29 30 31 32
    {
        $this->schema = $schema;
    }

33
    public function acceptTable(Table $table) : void
34
    {
35 36
        if ($table->isInDefaultNamespace($this->schema->getName())) {
            return;
37
        }
38 39

        $this->schema->dropTable($table->getName());
40
    }
Benjamin Morel's avatar
Benjamin Morel committed
41

42
    public function acceptSequence(Sequence $sequence) : void
43
    {
44 45
        if ($sequence->isInDefaultNamespace($this->schema->getName())) {
            return;
46
        }
47 48

        $this->schema->dropSequence($sequence->getName());
49 50
    }

51
    public function acceptForeignKey(Table $localTable, ForeignKeyConstraint $fkConstraint) : void
52
    {
53 54 55
        // The table may already be deleted in a previous
        // RemoveNamespacedAssets#acceptTable call. Removing Foreign keys that
        // point to nowhere.
56
        if (! $this->schema->hasTable($fkConstraint->getForeignTableName())) {
57
            $localTable->removeForeignKey($fkConstraint->getName());
58

59 60 61
            return;
        }

62
        $foreignTable = $this->schema->getTable($fkConstraint->getForeignTableName());
63 64
        if ($foreignTable->isInDefaultNamespace($this->schema->getName())) {
            return;
65
        }
66 67

        $localTable->removeForeignKey($fkConstraint->getName());
68 69
    }
}