RemoveNamespacedAssets.php 2.1 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\DBAL\Schema\Visitor;

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

/**
Benjamin Morel's avatar
Benjamin Morel committed
11
 * Removes assets from a schema that are not in the default namespace.
12 13 14 15 16 17 18 19 20
 *
 * 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.
 */
21
class RemoveNamespacedAssets extends AbstractVisitor
22
{
23
    /** @var Schema */
24 25 26
    private $schema;

    /**
Benjamin Morel's avatar
Benjamin Morel committed
27
     * {@inheritdoc}
28 29 30 31 32 33 34
     */
    public function acceptSchema(Schema $schema)
    {
        $this->schema = $schema;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
35
     * {@inheritdoc}
36 37 38
     */
    public function acceptTable(Table $table)
    {
39 40
        if ($table->isInDefaultNamespace($this->schema->getName())) {
            return;
41
        }
42 43

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

46
    /**
Benjamin Morel's avatar
Benjamin Morel committed
47
     * {@inheritdoc}
48 49 50
     */
    public function acceptSequence(Sequence $sequence)
    {
51 52
        if ($sequence->isInDefaultNamespace($this->schema->getName())) {
            return;
53
        }
54 55

        $this->schema->dropSequence($sequence->getName());
56 57 58
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
59
     * {@inheritdoc}
60 61 62
     */
    public function acceptForeignKey(Table $localTable, ForeignKeyConstraint $fkConstraint)
    {
63 64 65
        // The table may already be deleted in a previous
        // RemoveNamespacedAssets#acceptTable call. Removing Foreign keys that
        // point to nowhere.
66
        if (! $this->schema->hasTable($fkConstraint->getForeignTableName())) {
67 68 69 70
            $localTable->removeForeignKey($fkConstraint->getName());
            return;
        }

71
        $foreignTable = $this->schema->getTable($fkConstraint->getForeignTableName());
72 73
        if ($foreignTable->isInDefaultNamespace($this->schema->getName())) {
            return;
74
        }
75 76

        $localTable->removeForeignKey($fkConstraint->getName());
77 78
    }
}