PostgreSQL DB のアップグレードは brew postgresql-upgrade-database が便利


Homebrew で PostgreSQL をインストールしていると、`brew update && brew upgrade` を実行してアップデートした際、PostgreSQL もアップデートされ、バージョンの不一致によって動かなくなることがあります。

## エラー例: `PG::ConnectionBad` (Rails の場合)

![Rails - PG::ConnectionBad](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1857/81751166-ebcb-e2bb-b8f1-a6e3a3b0f6db.png "Kobito.zFAY7M.png")


上記エラーメッセージを見ると『PG (PostgreSQL) 周りの影響かな...? 🤔💭』と推測できるので、実際に PostgreSQL コマンドを実行してみると、PostgreSQL のアップデートには個別に対応する必要があることが分かります 🧐✨

```bash
╭─○ yasulab ‹2.6.5› ~/coderdojo.jp
╰─○ pg_ctl -D /usr/local/var/postgres start 

waiting for server to start....2020-02-29 10:35:46.814 JST [42482] FATAL:  database files are incompatible with server

2020-02-29 10:35:46.814 JST [42482] DETAIL:  The data directory was initialized by PostgreSQL version 11, which is not compatible with this version 12.2.

 stopped waiting

pg_ctl: could not start server
Examine the log output.
```

## カンタンな解決方法

PostgreSQL のデータベースをこれを解決するためには PostgreSQL のドキュメントを読みながら１つずつコマンドを打っていく (例: [Migrating Homebrew Postgres to a New Version](https://olivierlacan.com/posts/migrating-homebrew-postgres-to-a-new-version/)) 必要があります :sweat_drops: 

しかし...!! 現在は**2018年から導入された [brew postgresql-upgrade-database コマンド](https://github.com/Homebrew/homebrew-core/pull/21244)**を使うと Homebrew がまとめて対応してくれて便利です :relieved: :sparkles: 

```bash
╭─○ yasulab ‹2.6.5› ~/coderdojo.jp
╰─○ brew postgresql-upgrade-database

==> brew install postgresql@11
==> Downloading https://homebrew.bintray.com/bottles/postgresql@11-11.7.catalina.bottle.tar.gz
==> Downloading from https://akamai.bintray.com/d9/d9c41a81b4314a10ba40636a2eddf2c48f15c2563754a6fcfd75a20914
######################################################################## 100.0%
==> Pouring postgresql@11-11.7.catalina.bottle.tar.gz
==> /usr/local/Cellar/postgresql@11/11.7/bin/initdb --locale=C -E UTF-8 /usr/local/var/postgresql@11
==> Caveats
To migrate existing data from a previous major version of PostgreSQL run:
  brew postgresql-upgrade-database

postgresql@11 is keg-only, which means it was not symlinked into /usr/local,
because this is an alternate version of another formula.

If you need to have postgresql@11 first in your PATH run:
  echo 'export PATH="/usr/local/opt/postgresql@11/bin:$PATH"' >> ~/.zshrc

For compilers to find postgresql@11 you may need to set:
  export LDFLAGS="-L/usr/local/opt/postgresql@11/lib"
  export CPPFLAGS="-I/usr/local/opt/postgresql@11/include"

For pkg-config to find postgresql@11 you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/postgresql@11/lib/pkgconfig"


To have launchd start postgresql@11 now and restart at login:
  brew services start postgresql@11
Or, if you don't want/need a background service you can just run:
  pg_ctl -D /usr/local/var/postgresql@11 start
==> Summary
🍺  /usr/local/Cellar/postgresql@11/11.7: 3,192 files, 36.5MB
==> Upgrading postgresql data from 11 to 12...
waiting for server to start....2020-02-29 10:40:09.308 JST [44314] LOG:  listening on IPv6 address "::1", port 5432
2020-02-29 10:40:09.308 JST [44314] LOG:  listening on IPv4 address "127.0.0.1", port 5432
2020-02-29 10:40:09.309 JST [44314] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432"
2020-02-29 10:40:09.344 JST [44315] LOG:  database system was interrupted; last known up at 2020-02-28 11:30:09 JST
2020-02-29 10:40:09.662 JST [44315] LOG:  database system was not properly shut down; automatic recovery in progress
2020-02-29 10:40:09.667 JST [44315] LOG:  redo starts at 0/39B8650
2020-02-29 10:40:09.667 JST [44315] LOG:  invalid record length at 0/39B8730: wanted 24, got 0
2020-02-29 10:40:09.667 JST [44315] LOG:  redo done at 0/39B86F8
2020-02-29 10:40:09.683 JST [44314] LOG:  database system is ready to accept connections
 done
server started
waiting for server to shut down....2020-02-29 10:40:10.039 JST [44314] LOG:  received fast shutdown request
2020-02-29 10:40:10.041 JST [44314] LOG:  aborting any active transactions
2020-02-29 10:40:10.041 JST [44314] LOG:  background worker "logical replication launcher" (PID 44321) exited with exit code 1
2020-02-29 10:40:10.042 JST [44316] LOG:  shutting down
2020-02-29 10:40:10.048 JST [44314] LOG:  database system is shut down
 done
server stopped
==> Moving postgresql data from /usr/local/var/postgres to /usr/local/var/postgres.old...
==> Creating database...
The files belonging to this database system will be owned by user "yasulab".
This user must also own the server process.

The database cluster will be initialized with locale "ja_JP.UTF-8".
initdb: could not find suitable text search configuration for locale "ja_JP.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 dynamic shared memory implementation ... posix
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting default time zone ... Asia/Tokyo
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

initdb: 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:

    /usr/local/opt/postgresql/bin/pg_ctl -D /usr/local/var/postgres -l logfile start

==> Migrating and upgrading data...
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* data types in user tables                 ok
Checking for contrib/isn with bigint-passing mismatch       ok
Checking for tables WITH OIDS                               ok
Checking for invalid "sql_identifier" user columns          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 in the new cluster                        ok
Deleting files from new pg_xact                             ok
Copying old pg_xact 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
==> Upgraded postgresql data from 11 to 12!
==> Your postgresql 11 data remains at /usr/local/var/postgres.old
```

## ちなみに...

１点、過去に[同コマンドでアップグレードをしたことがある](https://qiita.com/yasulab/items/ed387a3c54e8d9c6a4b5#homebrew%E7%B5%8C%E7%94%B1%E3%81%A7%E5%85%AC%E5%BC%8F%E6%83%85%E5%A0%B1%E3%81%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%E3%81%99%E3%82%8B%E6%96%B9%E6%B3%95-scroll)と、`postgres.old` というディレクトが残っているため、次のように実行途中で止まる場合もあります。

```bash
╭─○ yasulab ‹2.6.5› ~/coderdojo.jp
╰─○ brew postgresql-upgrade-database

Error: /usr/local/var/postgres.old already exists!
Remove it if you want to upgrade data automatically.
```

上記メッセージにあるように削除しても良いですが、適当な名前にリネームしておいても解決するので、削除したくない場合は適宜リネームしておくとより安心ですね :relieved: :sparkles:

[![CoderDojo Japan Top.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1857/9da82678-f100-7197-fa66-9cb328c9b2d8.png "CoderDojo Japan Top.png")](https://coderdojo.jp)

## 関連記事

- [Rails で DB に接続できなくなったときの考え方 - Qiita](https://qiita.com/yasulab/items/ed387a3c54e8d9c6a4b5)
- [brew-postgresql-upgrade-database: add new command. #21244 - GitHub](https://github.com/Homebrew/homebrew-core/pull/21244) 
- [Migrating Homebrew Postgres to a New Version - Olivier Lacan](https://olivierlacan.com/posts/migrating-homebrew-postgres-to-a-new-version/)