[MacOS] Homebrew で PostgreSQL をインストールする手順

Mac に Homebrew で postgresql をインストールしたので手順をご紹介します。

PostgreSQL

postgresql のインストール

まず brew コマンドで postgresql をインストールします。

Homebrew をインストールしていない方は、以下を参考にして下さい。

brew install postgresql

PostgreSQL のデータベース初期化

initdb /usr/local/var/postgres -E utf8 --no-locale

自動起動の設定

ln -sfv /usr/local/opt/postgresql/*.plist ~/Library/LaunchAgents
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

環境変数 PGDATA の設定

環境変数 PGDATA を設定すると pg_ctl での起動停止時に -D の引数を渡さなくてよくなります。

export PGDATA=/usr/local/var/postgres

起動コマンド

pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
 
# 環境変数PGDATAの設定をしていれば以下の様に省略できます
pg_ctl -l /usr/local/var/postgres/server.log start

終了コマンド

pg_ctl stop -s -m fast
 
# 環境変数PGDATAの設定をしていれば以下の様に省略できます
pg_ctl -D /usr/local/var/postgres stop -s -m fast

postgres ユーザの作成

brew でインストールした場合 postgres ユーザは作成されないようです。

$USER がスーパーユーザとして作成されます。スーパーユーザーをそのまま使うのはよくないので、新しくユーザを作成します。

$ createuser -P username
# usernameの部分は新規作成するユーザの名前
# パスワードとスーパーユーザにするかどうかを入力する

ユーザがちゃんと作成されたかの確認は下記のコマンドでできます。

psql -q -c'select * from pg_user' postgres

Ruby で postgresql を使うために gem で pg をインストールしておきます。

env ARCHFLAGS="-arch x86_64" gem install pg

 
ちなみに、brew info postgresql コマンドを実行すると以下のように詳細が読めます。

If builds of PostgreSQL 9 are failing and you have version 8.x installed,
you may need to remove the previous version first. See:
  https://github.com/mxcl/homebrew/issues/issue/2510
 
To build plpython against a specific Python, set PYTHON prior to brewing:
  PYTHON=/usr/local/bin/python  brew install postgresql
See:
  http://www.postgresql.org/docs/9.0/static/install-procedure.html
 
 
If this is your first install, create a database with:
  initdb /usr/local/var/postgres
 
If this is your first install, automatically load on login with:
  mkdir -p ~/Library/LaunchAgents
  cp /usr/local/Cellar/postgresql/9.0.4/org.postgresql.postgres.plist ~/Library/LaunchAgents/
  launchctl load -w ~/Library/LaunchAgents/org.postgresql.postgres.plist
 
If this is an upgrade and you already have the org.postgresql.postgres.plist loaded:
  launchctl unload -w ~/Library/LaunchAgents/org.postgresql.postgres.plist
  cp /usr/local/Cellar/postgresql/9.0.4/org.postgresql.postgres.plist ~/Library/LaunchAgents/
  launchctl load -w ~/Library/LaunchAgents/org.postgresql.postgres.plist
 
Or start manually with:
  pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
 
And stop with:
  pg_ctl -D /usr/local/var/postgres stop -s -m fast
 
 
Some machines may require provisioning of shared memory:
  http://www.postgresql.org/docs/current/static/kernel-resources.html#SYSVIPC
 
If you want to install the postgres gem, including ARCHFLAGS is recommended:
    env ARCHFLAGS="-arch x86_64" gem install pg
 
To install gems without sudo, see the Homebrew wiki.

以上です。

参考情報