Railsアプリケーションの開発環境を構築するときに時々はまります。 ローカルにインストールされているPostgreSQLを使うとアプリケーションごとにPostgreSQLのユーザーが微妙に違うことがあります。
例えばpostgresというユーザーがないと次のようなエラーが起きます。
~ bundle exec rails db:create 2022-03-02 15:00:59.447 JST [52724] FATAL: role "postgres" does not exist connection to server at "localhost" (::1), port 5432 failed: FATAL: role "postgres" does not exist Couldn't create 'xxxx' database. Please check your configuration. rails aborted! ActiveRecord::NoDatabaseError: connection to server at "localhost" (::1), port 5432 failed: FATAL: role "postgres" does not exist
というわけでpostgresというユーザーを作成します。シェル上で次のコマンドを実行します。
createuser postgres
ふたたびrails db:create
します。
~ bundle exec rails db:create 2022-03-02 15:08:44.447 JST [52953] ERROR: permission denied to create database 2022-03-02 15:08:44.447 JST [52953] STATEMENT: CREATE DATABASE "xxxx" ENCODING = 'unicode' PG::InsufficientPrivilege: ERROR: permission denied to create database Couldn't create 'xxxx' database. Please check your configuration. rails aborted! ActiveRecord::StatementInvalid: PG::InsufficientPrivilege: ERROR: permission denied to create database Caused by: PG::InsufficientPrivilege: ERROR: permission denied to create database Tasks: TOP => db:create (See full trace by running task with --trace)
データベースを作成する権限が足りていません。 権限を追加しましょう。
~ psql postgres psql (14.2) Type "help" for help. postgres=# ALTER USER postgres CREATEDB; ALTER ROLE postgres=# \du List of roles Role name | Attributes | Member of -----------------+------------------------------------------------------------+----------- postgres | Create DB | {} shigerunakajima | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
みたびrails db:create
します。
~ bundle exec rails db:create Created database 'xxxx'
成功します。
参考
- FATAL: role "postgres" does not exist を解決した話。 - Qiita
- Granting a user account permission to create databases in PostgreSQL - Database Administrators Stack Exchange
*1:HomebrewでインストールしたPostgreSQLなので、macOSのログインユーザーと同じ名前のユーザーもいます。