Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird Random names in constrains generated by Doctrine2 (Symfony2)

For some reason when I generate migration using

php app/console doctrine:migrations:diff

I get weird names for constrains & indexes like FK_FFE561C6BE3BD8D4 & IDX_FFE561C6BE3BD8D4:

$this->addSql("ALTER TABLE agent_task ADD agentConfig_id INT UNSIGNED DEFAULT NULL, DROP agent_id");
$this->addSql("ALTER TABLE agent_task ADD CONSTRAINT FK_FFE561C6BE3BD8D4 FOREIGN KEY (agentConfig_id) REFERENCES agent_config (id)");
$this->addSql("CREATE INDEX IDX_FFE561C6BE3BD8D4 ON agent_task (agentConfig_id)");

The entity code snippet:

    /**
     * @var AgentConfig
     *
     * @ORM\ManyToOne(targetEntity="AgentConfig",inversedBy="agentTasks")
     * @ORM\JoinColumn(name="agent_config_id", referencedColumnName="id")
     */
    private $agentConfig;

Is there any way to define the names for those?

UPDATE

I tried indexes, but it didn't help.

/**
 * AgentTaskConfig
 *
 * @ORM\Table(name="agent_task_config", indexes={@ORM\index(name="agent_task_config_task_id", columns={"task_id"})})
 * @ORM\Entity
 */
class AgentTaskConfig

Still happening:

$this->addSql("ALTER TABLE agent_task_config DROP FOREIGN KEY fk_agent_task_id");
$this->addSql("ALTER TABLE agent_task_config ADD CONSTRAINT FK_7FEDF0EF8DB60186 FOREIGN KEY (task_id) REFERENCES agent_task (id)");
like image 980
vladykx Avatar asked Sep 20 '13 11:09

vladykx


2 Answers

Having more time I investigated doctrine's (v2.4.x) SchemaTool.php that does the generation. It looks like they are using method:

Table#addUnnamedForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options=array())

which speaks for itself. It is marked as deprecated with link to:

Table#addForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options=array(), $constraintName = null)

This method has argument $constraintName, which is not used as of now. I guess the only way is to edit the Schema tool to use the latter method passing your own $constraintName.

The constraint name generation looks like this:

protected function _generateIdentifierName($columnNames, $prefix='', $maxSize=30)
{
    $hash = implode("", array_map(function($column) {
        return dechex(crc32($column));
    }, $columnNames));

    return substr(strtoupper($prefix . "_" . $hash), 0, $maxSize);
}
like image 102
vladykx Avatar answered Sep 28 '22 19:09

vladykx


You can define the indexes yourself on your entities

/**
 *
 * @ORM\Table(name="company", indexes={@ORM\Index(name="model_partner_idx", columns={"partner"})} )
 * @ORM\Entity
 */
class Company
like image 36
Thomas K Avatar answered Sep 28 '22 19:09

Thomas K