brew upgradeしたらpostgresqlもUpgradeされて起動できなくなった時の解決方法

# 背景

1. 問題の発端は、Brew upgradeして再起動したせいか、Postgresが動いていない。

```bash
psql postgres
psql: 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"?
```

2. 起動しようとした。

```
 pg_ctl -D /usr/local/var/postgres -w start
pg_ctl: another server might be running; trying to start server anyway
waiting for server to start....FATAL:  database files are incompatible with server
DETAIL:  The data directory was initialized by PostgreSQL version 9.5, which is not compatible with this version 9.6.3.
 stopped waiting
pg_ctl: could not start server
Examine the log output.
```

ちなみに今回は、9.5.4-> 9.6.3へのUpgrade。以下の解決策ないのバージョン部分は、自分のバージョンに合わせて変更が必要。

```
pg_config --version
PostgreSQL 9.6.3
psql -V
psql (PostgreSQL) 9.6.3
```


# 解決

基本https://gist.github.com/joho/3735740 これに従ってやってみる

## 解決策まとめ

```
1. launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
2. mv /usr/local/var/postgres /usr/local/var/postgres91
3. brew update
4. brew upgrade postgresql
5. initdb /usr/local/var/postgres -E utf8
6. pg_upgrade -b /usr/local/Cellar/postgresql/9.5.4/bin -B /usr/local/Cellar/postgresql/9.6.3/bin -d /usr/local/var/postgres95 -D /usr/local/var/postgres
(6-1.もしも失敗したら rm /usr/local/var/postgres/postmaster.pidする) 
7. cp cp /usr/local/Cellar/postgresql/9.6.3/homebrew.mxcl.postgresql.plist ~/Library/LaunchAgents/
8. pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

```

## 詳細

### 1

```
launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
```

### 2

```
mv /usr/local/var/postgres /usr/local/var/postgres95
```

### 3, 4

```
brew update
brew upgrade postgresql # ここではpostgresql 9.6.3 already installedとなって変更なし
```


### 5

```
initdb /usr/local/var/postgres -E utf8
```

#### 結果：失敗

```bash
The files belonging to this database system will be owned by user "nakamasato".
This user must also own the server process.

The database cluster will be initialized with locales
  COLLATE:  ja_JP.UTF-8
  CTYPE:    UTF-8
  MESSAGES: ja_JP.UTF-8
  MONETARY: ja_JP.UTF-8
  NUMERIC:  ja_JP.UTF-8
  TIME:     ja_JP.UTF-8
initdb: could not find suitable text search configuration for locale "UTF-8"
The default text search configuration will be set to "simple".

Data page checksums are disabled.

fixing permissions on existing directory /usr/local/var/postgres ... initdb: could not change permissions of directory "/usr/local/var/postgres": Operation not permitted
```

#### 原因

Onwerが自分でなくRootだったので変更

#### 解決策

```
sudo chown nakamasato /usr/local/var/postgres
```

####再度Initを試みる

```bash

± initdb /usr/local/var/postgres -E utf8
The files belonging to this database system will be owned by user "nakamasato".
This user must also own the server process.

The database cluster will be initialized with locales
  COLLATE:  ja_JP.UTF-8
  CTYPE:    UTF-8
  MESSAGES: ja_JP.UTF-8
  MONETARY: ja_JP.UTF-8
  NUMERIC:  ja_JP.UTF-8
  TIME:     ja_JP.UTF-8
initdb: could not find suitable text search configuration for locale "UTF-8"
The default text search configuration will be set to "simple".

Data page checksums are disabled.

fixing permissions on existing directory /usr/local/var/postgres ... ok
creating subdirectories ... ok
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting dynamic shared memory implementation ... posix
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

WARNING: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.

Success. You can now start the database server using:

    pg_ctl -D /usr/local/var/postgres -l logfile start
```

### 6

```bash

pg_upgrade -b /usr/local/Cellar/postgresql/9.5.4/bin -B /usr/local/Cellar/postgresql/9.6.3/bin -d /usr/local/var/postgres95 -D /usr/local/var/postgres
```

####結果: 失敗

```
*failure*
Consult the last few lines of "pg_upgrade_server.log" for
the probable cause of the failure.

There seems to be a postmaster servicing the new cluster.
Please shutdown that postmaster and try again.
Failure, exiting

```
####対応策
ぐぐってみると、stop してから、postmaster.pidを削除するとあるので試してみる

```bash
pg_ctl -D /usr/local/var/postgres/ stop
waiting for server to shut down...........failed
```

ストップできない、ぐぐってみると、postmaster.pidを消せば良いようなので、以下を実行

```
rm /usr/local/var/postgres/postmaster.pid
```

#### 再度`pg_upgrade`する

```
pg_upgrade -b /usr/local/Cellar/postgresql/9.5.4/bin -B /usr/local/Cellar/postgresql/9.6.3/bin -d /usr/local/var/postgres95 -D /usr/local/var/postgres

Performing Consistency Checks
-----------------------------
Checking cluster versions                                   ok
Checking database user is the install user                  ok
Checking database connection settings                       ok
Checking for prepared transactions                          ok
Checking for reg* system OID user data types                ok
Checking for contrib/isn with bigint-passing mismatch       ok
Checking for roles starting with 'pg_'                      ok
Creating dump of global objects                             ok
Creating dump of database schemas
                                                            ok
Checking for presence of required libraries                 ok
Checking database user is the install user                  ok
Checking for prepared transactions                          ok

If pg_upgrade fails after this point, you must re-initdb the
new cluster before continuing.

Performing Upgrade
------------------
Analyzing all rows in the new cluster                       ok
Freezing all rows on the new cluster                        ok
Deleting files from new pg_clog                             ok
Copying old pg_clog to new server                           ok
Setting next transaction ID and epoch for new cluster       ok
Deleting files from new pg_multixact/offsets                ok
Copying old pg_multixact/offsets to new server              ok
Deleting files from new pg_multixact/members                ok
Copying old pg_multixact/members to new server              ok
Setting next multixact ID and offset for new cluster        ok
Resetting WAL archives                                      ok
Setting frozenxid and minmxid counters in new cluster       ok
Restoring global objects in the new cluster                 ok
Restoring database schemas in the new cluster
                                                            ok
Copying user relation files
                                                            ok
Setting next OID for new cluster                            ok
Sync data directory to disk                                 ok
Creating script to analyze new cluster                      ok
Creating script to delete old cluster                       ok

Upgrade Complete
----------------
Optimizer statistics are not transferred by pg_upgrade so,
once you start the new server, consider running:
    ./analyze_new_cluster.sh

Running this script will delete the old cluster's data files:
    ./delete_old_cluster.sh
```

完成！


### 7

```
cp /usr/local/Cellar/postgresql/9.6.3/homebrew.mxcl.postgresql.plist ~/Library/LaunchAgents/
```

### 8
既にPostgresが動いているので必要なかった


# 確認

```
psql postgres
\list
```

これで前のバージョンにあったデータが全て存在するのを確認。