DonCallisto
DonCallisto

Reputation: 29932

Rename table name with Doctrine migrations

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?

Upvotes: 12

Views: 21398

Answers (2)

Musa Haidari
Musa Haidari

Reputation: 2267

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

Upvotes: 3

Crozin
Crozin

Reputation: 44396

  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.

Upvotes: 19

Related Questions