LoginSignup
0
0

More than 3 years have passed since last update.

【備忘録】Rails6でrails db:create実行時にPostgreSQLに接続できなかった時の対処の話

Posted at

なんの話か

Rails6を使って新しいアプリ開発をやろうとして、ローカルのPostgreSQLを使おうとしたら発生したエラーの解決までの話しです。正直ポスグレを今回初めて使用したため、エラーに対して根本的な原因や、仕様などを理解しながら解決できるのかわかりませんでした。エラー文を読みながら進めていくと、なんとなくどういう状態に陥っているのかがわかるエラーでしたが、どうしてもつまづいてしまった部分をSEの知り合いに助けていただきました。

起こったこと

rails _6.0.3.2_ new memo-app --database=postgresqlコマンドで、DBにポスグレを指定してアプリ作成し、
rails db:createでデータベースを作ろうとしたとき、下記のエラーに遭遇。

$ rails db:create
could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
Couldn't create 'APP_NAME_development' database. Please check your configuration.
rails aborted!
PG::ConnectionBad: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
***

要約すると、postgreSQLに接続できず、DBの作成に失敗しています。

やったこと① postgreSQLの再起動してstatusnの確認

$ brew services restart postgresql
Stopping `postgresql`... (might take a while)
==> Successfully stopped `postgresql` (label: homebrew.mxcl.postgresql)
==> Successfully started `postgresql` (label: homebrew.mxcl.postgresql)

を実行して、postgreSQLを再起動をかけて、

$ brew services list

で状態を確認したが、

Name       Status  User  Plist
postgresql error   yoshi /Users/yoshi/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

statusがエラーのまま。もちろんこのまま実行しても、最初のエラーが再び吐き出されるだけ。
local環境にはpostgreSQLがあって起動できるけど接続できる状況にないことがここでわかります。

やったこと②

ここでつまづいてどうしようもなかったので、SEの先輩に一言アドバイスをもらいました。
データディレクトリがどういう状態か確認してみよ、とアドバイスをいただき、

$ postgres -D /usr/local/var/postgres

で確認したところ、

FATAL:  database files are incompatible with server
***
DETAIL:  The data directory was initialized by PostgreSQL version 12, 
which is not compatible with this version 13.1.

という文章がでてくれました。DBファイルの互換性に問題があります。
Ver12で初期化された現在のデータディレクトリは、Ver13.1では互換性がないので使えません。
ということです。

最終的には

そうなると、アップデートすればいいのでは?という仮定に至り、

brew postgresql-upgrade-databaseでアップデートをかけて、
brew services restart postgresqlで再起動した上で、

再度DB作成してみたところ、

$ rails db:create
Created database 'memo_app_development'
Created database 'memo_app_test'

無事DBの作成に成功したので、解決しました。
根本的な原因は、いつのまにかVer12で作成されたDBに問題があったところです。
おそらく何が何だかわからず変なコマンド打ったりしていたのでこうなったのでは、と...。

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0