On peut avoir le besoin d'ajouter une colonne uuid (v4) à une table. C'est souvent un champ unique et NOT NULL.
Le problème que l'on rencontre à ce moment la est de peupler le champ.
Pour peupler le champ nous allons nous servir d'une fonction SQL. Elle permettra de générer un uuid au format voulu.
Dans notre exemple, nous allons ajouter une fonction ajouter un uuid v4.
Pour l'utiliser dans une migration passons par un trait.
1
2
3
4
5
6
7
8
9
10
11
12
trait UuidTrait{ private function requireUuidFunction() { // Add uuid_v4() function $this->addSql('DROP FUNCTION IF EXISTS uuid_v4'); $this->addSql(file_get_contents(__DIR__ . '/sql/uuid_v4.sql')); // Check if uuid_v4 function is available $this->addSql('SELECT uuid_v4()'); }}
<?phpnamespaceDoctrineMigrations;useApp\Infra\Bridge\Uuid\UuidTrait;useDoctrine\DBAL\Schema\Schema;useDoctrine\Migrations\AbstractMigration;finalclassVersionXXXXXXXXXXXXXXXXextendsAbstractMigration{useUuidTrait;publicfunctiongetDescription():string{return'Add uuid on [MY_TABLE_NAME]';}publicfunctionup(Schema$schema):void{$this->abortIf($this->connection->getDatabasePlatform()->getName()!=='mysql','Migration can only be executed safely on \'mysql\'.');$this->requireUuidFunction();$this->addSql('ALTER TABLE [MY_TABLE_NAME] ADD uuid VARCHAR(255) NOT NULL');$this->addSql('UPDATE [MY_TABLE_NAME] SET uuid = uuid_v4()');$this->addSql('CREATE UNIQUE INDEX [MY_INDEX_NAME] ON [MY_TABLE_NAME] (uuid)');}publicfunctiondown(Schema$schema):void{$this->abortIf($this->connection->getDatabasePlatform()->getName()!=='mysql','Migration can only be executed safely on \'mysql\'.');$this->addSql('DROP INDEX [MY_INDEX_NAME] ON customer_customers');$this->addSql('ALTER TABLE [MY_TABLE_NAME] DROP uuid');}}