Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping/toggling two MySQL databases

Tags:

mysql

We recently lost some data from our live DB. We restored an older backup as our current live DB, and have been repairing a more recent partially broken DB as a test DB. Both are running on the same server and the plan is the testing DB will replace the live DB as soon as we're happy the fixes are valid.

Is there an easy way to swap the two DBs, e.g. swap their names, so we can just switch which one is used by the website for some last-minute checks? i.e. we want to set the repaired DB as the live one, but be able to flip back without re-building/re-importing a whole exported version.

I don't know if MySQL allows renaming DBs in this way.

like image 675
Mr. Boy Avatar asked May 14 '26 13:05

Mr. Boy


1 Answers

To swap two database schemas that are named db1 and db2:

mysqladmin -uroot -pmypassword create swaptemp
mysqldump -uroot -pmypassword --routines db1 | mysql -u root -pmypassword swaptemp
mysqladmin -uroot -pmypassword drop db1
mysqladmin -uroot -pmypassword create db1
mysqldump -uroot -pmypassword --routines db2 | mysql -u root -pmypassword db1
mysqladmin -uroot -pmypassword drop db2
mysqladmin -uroot -pmypassword create db2
mysqldump -uroot -pmypassword --routines swaptemp | mysql -u root -pmypassword db2
mysqladmin -uroot -pmypassword drop swaptemp

Steps:

  1. Copy the lines into Notepad.
  2. Replace all references to "db1", "db2", "mypassword" (+ optionally "root") with your equivalents.
  3. Execute one by one on the command line (entering "y" when prompted).
like image 79
Steve Chambers Avatar answered May 16 '26 08:05

Steve Chambers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!