Rename table name with Doctrine migrations
Asked Answered
B

2

12

I've searched pretty much everywhere but I wasn't able to find anything.

Is there a command or a procedure to change the name of a table (so inside doctrine annotation) without loosing data?

Basically, something that will produce something like

RENAME TABLE old_table TO new_table;

or

ALTER TABLE old_table RENAME new_table;

MySQL commands taken from here

Should I write manually the migration file with doctrine:migrations:generate?

Burt answered 30/12, 2015 at 15:56 Comment(2)
Which database system do you use?Appeasement
@Appeasement MySQL, but I suppose that should exist a "universal" methodBurt
G
19
  1. Change table name for given entity.

    /** @Entity @Table(name="new_table_name") */
    class MyEntity { ... }
    
  2. Generate a new migration.

  3. Erase contents of up() and down() methods and replace them with custom SQL (ALTER TABLE ... RENAME TO ...).

Keep in mind that migration generator is meant as utility/semi-automatic tool.

Gauss answered 30/12, 2015 at 16:18 Comment(2)
Yes, so, basically, I can reach the same by running php app/console doctrine:migrations:generate (that, indeed, is what I've done 'till now)Burt
This doesn't handle updating foreign key constraints.Worldling
T
2

I found the best possible way is to use a two-step / two-migration approach. With the 1st migration rename the table only, and with the 2nd migration take care of the renaming parts, e.g. FKs.

The steps I took:

  1. Rename the PHP entity, lets say App\Entity\OldName to App\Entity\NewName
  2. Create a new migration, e.g. symfony console make:migration
  3. Replace the up() with ALTER TABLE old_name RENAME new_name; and down() with ALTER TABLE new_name RENAME old_name;. In other words, this migration only renames the table itself, without FKs, indexes, etc.
  4. Run the migration, e.g. symfony console doctrine:migrations:migrate -n
  5. Again, create a new migration symfony console make:migration. The generated code for this migration handles all the FKs, columns rename (if you did any in the PHP entity), indexes, etc.
  6. Run this migration too, e.g. symfony console doctrine:migrations:migrate -n
Tamie answered 3/1 at 5:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.