Just do IT

思うは招く

Rails 6 で DB を SQLite3 から PostgreSQL に変更するのはコマンド一発

Railsアプリをrails newしたとき、DBをPostgreSQLにするオプションを忘れていた。

「database.yml を自分で編集するのめんどくさいなぁ・・・」と思っていたら、Rails 6 からはコマンドひとつで変更できるようになっていた。

Rails 6 からはコマンド一発

たとえば、PostgreSQL に変更したい場合は以下のコマンドを叩く。

#postgresqlに変更
rails db:system:change --to=postgresql

これで database.ymlやGemfileが自動で変更される。なんて便利なんだ!

ちなみにPostgreSQLだけじゃなくMySQLなどにも変更できるとのこと。

経緯

以下はDHHが上げたIssue。

Add rails db:change SYSTEM=postgresql|mysql|whatever · Issue #34710 · rails/rails

It's common to create a new Rails app without specifying the database system upfront. That means you'll get the sqlite system by default, which is great until you actually have to deploy in production. Then you usually want to swap sqlite out with something else, like MySQL or PostgreSQL. Doing so is too much of a hassle today.

I'd therefore like to see that we add a command that makes this easy. Running rails db:change SYSTEM=postgresql should overwrite config/database.yml with the database.yml config that we already keep in Railties for when a new app is started with --database=postgresql. It should also replace the gem "sqlite" line in the Gemfile with the PostgreSQL line.

要約

Railsアプリ作るときってな、データベース指定しないことが多いやんか。つまりデフォルトのsqlite使うってことなんやけど、本番にデプロイするとき、結局はデータベース変えるやん?でも、今ってデータベース変える作業まぁまぁダルいやん?コマンド一発で簡単にできひんかなぁ?〜以下略〜」

以下はIssueにたいするPR。感謝🙏

Add rails db:system:change command by gmcgibbon · Pull Request #34832 · rails/rails

参考

🥇 Rails6「SQLite ⇆ MySQL ⇆ PostgreSQL」データベースを移行(変更)する方法 | ゴリログ