postgresqlのユーザー追加からそのユーザーでログインするまでの流れをまとめてみた

前のエントリではpostgresqlのインストールからDBの立ちあげまでを行ったので、今度はユーザーを作ってそのユーザーでログインするまでの流れをまとめてます。

【目次】

・ユーザーの作成
・databaseの作成
・ユーザーのパスワード設定
・ユーザーに対してあるDBへの権限付与
・作成したユーザーでのログイン


・ユーザーの作成

postgressqlを起動させるには初期化時に作成された「postgres」ユーザーでログインする必要があります。
なので↓でまずはpostgresユーザーに切り替え。

$ su - postgres

その状態で

-bash$ createuser user_name

とするとユーザーが作成されます。
ちなみにuseraddでもオプションがこんなに。。。
http://www.postgresql.jp/document/8.3/html/app-createuser.html
覚える必要はないと思いますが、ちょっとだけ確認。

・databaseの作成

dbの作成はこんな感じで。
こちらもオプションこんなにあります。
https://www.postgresql.jp/document/7.4/html/app-createdb.html

-bash$ createdb db_name

・ユーザーのパスワード設定

ユーザーのパスワード設定はこのように設定します。
こちらもオプションは↓のような感じに。
https://www.postgresql.jp/document/pg653doc/j/user/sql-alteruser.htm

mydb=> alter user user_name with password '*********';

・ユーザーに対してあるDBへの権限付与

あるユーザーの特定のDBへのアクセス権限を設定したい場合は、

mydb=> grant all on database db_name TO user_name;

selectやinsertごとに権限付与も可能
http://www.postgresql.jp/document/7.2/reference/sql-grant.html


・作成したユーザーでのログイン

先ほど作成したuserで先ほど作成したDBにログインしますがその前にpostgresの再起動を

$ service postgresql-9.3 restart

その後↓のようにするとログインできます。

//user_nameでdb_nameに接続
mydb=> psql -U user_name -h host db_name


【追記】
postgresql.conf(/var/lib/pgsql/9.3/data/postgresql.conf)というファイルで今回どこからでもアクセスできるように以下の点も変更しています。

#変更前
listen_addresses = "localhost"

#変更後
listen_addresses = "*"

どのユーザーがどういう認証方式で接続出来るのかの設定をするため
pg_hba.conf(/var/lib/pgsql/9.3/data/pg_hba.conf)を編集

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only

# IPv4 local connections:
#この行↓追加
host    all              user_name  0.0.0.0/0                 md5


# IPv6 local connections:
#この行↓追加(この表記が必要なワケが理解できない。。。)
host    all              user_name  ::1/128                 md5

デフォルトルートとは
http://www.infraexpert.com/study/routing3.html

pg_hba.confファイル
https://www.postgresql.jp/document/8.4/html/auth-pg-hba-conf.html



PostgreSQL全機能リファレンス (アドバンストリファレンスシリーズ)

PostgreSQL全機能リファレンス (アドバンストリファレンスシリーズ)