Migrate Homebrewed MySQL from OS X to macOS

So Apple has released newer version of its OS, reusing the old name macOS. As always I upgrade my working system to macOS, then homebrewed MySQL won’t work anymore, to be precise, it cannot do write anymore.
In this post I will write down what I’ve done to make it work again, even with all data kept. Hope it will help someone digging around for hours but still no clue.
Basically what I do is to reinstall MySQL with homebrew. As usual I did a upgrade with:
$ brew upgrade mysqlbut no, no difference, still cannot write.
Then I removed MySQL with:
$ brew uninstall mysql
$ brew prune mysql
$ brew cleanupAfter this all MySQL binaries are removed from my system, but still there were database default files and databases left in /usr/local/var/mysql. And here the databases and innodb files should be kept.
I copied all these to another place and delete every other thing:
$ cp /usr/local/var/mysql/ib* /path/to/my_back_up_folder/.
$ cp -R /usr/local/var/mysql/{database1, database2} /path/to/my_back_up_folder/.
$ rm -rf /usr/local/var/mysqlThen I did a fresh MySQL install with homebrew and copied back all the backuped files, start MySQL:
$ homebrew install MySQL
$ cp -R /path/to/my_back_up_folder/{database1, database2} /usr/local/var/mysql/.
$ brew services start mysqlFinally MySQL is working, all my old databases are all kept!