LoginSignup
3
0
はじめての記事投稿

PostgreSQLでroleを作成する /PG::ConnectionBad: FATAL: role "postgres" does not exist

Last updated at Posted at 2023-06-18

まずはじめに

今回の記事はあくまで自分のメモ用みたいなものです。
そのため、間違っていることや、表現の誤りなども含むと思いますので、鵜呑みにはしないでください。
また、心の優しい方がいれば、そっと間違いを指摘していただけると学びの励みになるので、すごく嬉しいです。。。

エラー内容

Rails, PostgreSQLで環境構築をしていると、以下のエラーが発生。

ActiveRecord::ConnectionNotEstablished: FATAL: role "postgres" does not exist
Caused by:
PG::ConnectionBad: FATAL: role "postgres" does not exist

結論

postgresというroleがないので、以下のコマンドで作成

CREATE ROLE postgres SUPERUSER;

(注)SUPERUSERは、最強の権限なので、良くないという記事も拝見したので、おすすめはしません。

原因

まずエラー文から、postgresのroleがないよー。と言われている。
roleとは、、?の状態だったので、まずはpostgresのroleについて調べる。

roleとは

PostgreSQLのroleとは、ユーザやグループがデータベースへアクセスすることを管理するための仕組み。
最初にPostgreSQLが立ち上がるとpostgresという名前のロールが作成されている。このロールは何でもできるスーパーユーザーだ。

なるほど、、。でも今回は"postgres" does not existなのか。とりあえず、roleがあるか確認してみよう。

roleの確認

まず、postgresに入る。

psql postgres

*もしpostgresを起動してなかったら、以下のコマンドで接続。

brew services start postgresql

以下のコマンドで、roleの確認。(\は, option + ¥)

postgres=# \du
                                   List of roles
 Role name |                         Attributes                         | Member of
-----------+------------------------------------------------------------+-----------
 xxx    | Superuser, Create role, Create DB, Replication, Bypass RLS | {}

あれ、Role nameにpostgresがない。(エラー文にそう書いてましたよね)
じゃあ作ればいいんだ!  (単細胞)

roleの作成

CREATE ROLE postgres SUPERUSER; 

上の結論でも書きましたが、SUPERUSERは、最強の権限になるので、あまりおすすめはしません。

よし、できた!role確認!!

postgres=# \du
                                   List of roles
 Role name |                         Attributes                         | Member of
-----------+------------------------------------------------------------+-----------
 xxx    | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
 postgres    | Superuser, Create role, Create DB, Cannot Login| {}

Cannot Login??

結局↑こいつのせいでログインできなかったので、以下のコマンドでログインの権限も持たせて、無事解決しました。

ALTER ROLE postgres LOGIN;
 xxx    | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
 postgres    | Superuser, Create role, Create DB | {}

まとめ

roleとは?でもありましたが、

最初にPostgreSQLが立ち上がるとpostgresという名前のロールが作成されている。

でも実際私の場合、postgresという名前のロールは作成されていませんでした。
不思議に思い、調べてみたところ、以下の内容を見つけました。

homebrew経由でインストールした際のmacユーザーのrole名が自動的に作成されている

😇😇😇

3
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
3
0