はじめに
Railsで新規アプリを作成した際に、DBの作成に失敗しました。
DBはPostgreSQLに指定して作成していたのですが、エラーの原因はPostgreSQLのバージョンの違いによるものでした。
今回は、その際の対処方法をまとめておきたいと思います。
環境
Rails new
$ rails new sample_app -d postgresql
-d 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 'sample_app_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"? /~/sample_app/bin/rails:9:in `<top (required)>' /~/sample_app/bin/spring:15:in `<top (required)>' bin/rails:3:in `load' bin/rails:3:in `<main>' Tasks: TOP => db:create (See full trace by running task with --trace)
上記のようなエラーが発生しました。
postgresql.log
エラーの原因を特定するために、PostgreSQLのログを確認することにしました。
ログは以下のディレクトリから確認することができます。
file:///usr/local/var/log/postgres.log
ログの内容はこのようになっていました。
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.
データディレクトリがversion 12であるため、version 13.1との互換性がないことが原因でした。
PostgreSQLのバージョンアップ
バージョンアップの前に、サービスを停止しておきます。
$ brew services stop postgresql
PostgreSQLをバージョンアップします。
$ brew postgresql-upgrade-database
サービスを再起動します。
$ brew services restart postgresql
再度、rails db:create
PostgreSQLのバージョンアップができたので、再度DBを作成してみます。
$ rails db:create > Created database 'sample_app_development' > Created database 'sample_app_test'
無事、DBを作成することができました。
ログを確認してみると、このようになっており、エラーが解消されました!
LOG: starting PostgreSQL 13.1 on x86_64-apple-darwin19.6.0, compiled by Apple clang version 12.0.0 (clang-1200.0.32.27), 64-bit LOG: listening on IPv6 address "::1", port 5432 LOG: listening on IPv4 address "127.0.0.1", port 5432 LOG: listening on Unix socket "/tmp/.s.PGSQL.5432" LOG: database system was shut down at 2021-01-06 01:03:11 JST LOG: database system is ready to accept connections