Rails で DB に接続できなくなったときの考え方


Rails サーバーを立ち上げてデータベースに繋がらなくなった経験が稀によくあると思いますが、そういうときって皆さんはどう対処していますか? 🤔💭 エラーメッセージでググってアレコレ試す方法もあると思いますし、心の目でデバッグする方法あると思います :pray: :relieved: 

各自の環境や状況によって採るべきアクションは異なると思いますが、僕は「なるべく公式情報を追って解決する」という方法を採ることが多いです。色々なやり方があって良いかなと思いますが、その1つのやり方としてご参考になれば幸いです (＞人＜ )✨

## 「なんかエラー出た!」からの原因調査→対策例

今回は僕が実際に遭遇した例をベースに、エラーに遭遇するところから、原因を1つずつ調べていき、最終的に対処するところまでの流れを順々にまとめていきます。ちなみに題材とするRailsアプリケーションはこちら。

CoderDojo Japan - 子どものためのプログラミング道場
https://coderdojo.jp/

GitHub - coderdojo-japan/coderdojo.jp (OSS)
https://github.com/coderdojo-japan/coderdojo.jp

![Kobito.sISNA2.png](https://qiita-image-store.s3.amazonaws.com/0/1857/6bf30e86-5073-6efd-4a27-9b99eafae597.png "Kobito.sISNA2.png")


まずはエラーに出会うところから。

### エラーとの出会い :sparkling_heart: 

```bash
╭─○ yasulab ‹2.5.3› ~/coderdojo.jp
╰─○ rails s

WARNING: Nokogiri was built against LibXML version 2.9.7, but has dynamically loaded 2.9.4
=> Booting WEBrick
=> Rails 5.1.6.1 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
[2018-12-27 11:55:12] INFO  WEBrick 1.4.2
[2018-12-27 11:55:12] INFO  ruby 2.5.3 (2018-10-18) [x86_64-darwin17]
[2018-12-27 11:55:12] INFO  WEBrick::HTTPServer#start: pid=12570 port=3000

Started GET "/" for ::1 at 2018-12-27 11:55:15 +0900
PG::ConnectionBad (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"?
):
```

エラーメッセージを見ると PG (PostgreSQL) が原因であることがわかりますね。ただ上記の情報だけだと何でデータベースに繋がらないのかまでは分からないので、ひとまず現在 PostgreSQL がそもそも動いているのかどうかを調べてみます :mag: 

### Postgre SQLの現在の状態を調べる :mag: 

```bash
╭─○ yasulab ‹2.5.3› ~/coderdojo.jp
╰─○ pg_ctl -D /usr/local/var/postgres start # パスは環境によって違う

waiting for server to start....2018-12-28 19:53:07.847 EST [5097] FATAL:  database files are incompatible with server
2018-12-28 19:53:07.847 EST [5097] DETAIL:  The data directory was initialized by PostgreSQL version 10, which is not compatible with this version 11.1.  # <= コレが原因っぽい 👀
 stopped waiting
pg_ctl: could not start server
Examine the log output.
```

状態を調べてみると、今回の場合は「DB のバージョンが異なるとうまく動作しなくなる (incompatible になる) から」ということが分かりました。なるほど! そういえば最近 `brew update` や `brew upgrade` をした記憶があるので、たぶんそれが要因でしょう :sweat_smile: 

バージョンを上げる際には Homebrew を使っていたので、Homebrew 経由で公式情報にアクセスしてみるとなんかいい情報が見つかりそうです （公式情報にはいい感じのシンプルな回答が載ってることが多い印象です） 🤔💭

### Homebrew経由で公式情報にアクセスする方法 :scroll: 

```bash
╭─○ yasulab ‹2.5.3› ~/coderdojo.jp
╰─○ brew info postgresql

postgresql: stable 11.1 (bottled), HEAD
Object-relational database system
https://www.postgresql.org/
Conflicts with:
  postgres-xc (because postgresql and postgres-xc install the same binaries.)
/usr/local/Cellar/postgresql/10.4 (3,389 files, 39.2MB)
  Poured from bottle on 2018-07-25 at 23:24:07
/usr/local/Cellar/postgresql/11.1 (3,548 files, 40.3MB) *
  Poured from bottle on 2018-12-23 at 12:30:47
From: https://github.com/Homebrew/homebrew-core/blob/master/Formula/postgresql.rb
==> Dependencies
Build: pkg-config ✔
Required: icu4c ✔, openssl ✔, readline ✔
Optional: python ✘
==> Options
--with-python
	Enable PL/Python3
--HEAD
	Install HEAD version
==> Caveats
To migrate existing data from a previous major version of PostgreSQL run:
  brew postgresql-upgrade-database # <= いい感じの回答を見つけた! 👀✨

To have launchd start postgresql now and restart at login:
  brew services start postgresql
Or, if you don't want/need a background service you can just run:
  pg_ctl -D /usr/local/var/postgres start
==> Analytics
install: 88,258 (30 days), 185,674 (90 days), 701,483 (365 days)
install_on_request: 75,475 (30 days), 163,418 (90 days), 594,559 (365 days)
build_error: 0 (30 days)
```

いい感じの回答が見つかりました! ここまで来ると「勝った （完）」みたいな気持ちになりますが、油断せずに公式情報に沿って対応していきます :wrench: :dash: 

:pencil: _NOTE：公式情報に沿って対応すると直ることがほとんどかなと思いますが、より複雑な環境だと原因が1つだけではないかもしれません。その場合も上記のように1つずつ公式情報を見ながら進めると良さそうです。_

### 公式情報に沿って対応 :wrench: :dash: 

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

==> brew install postgresql@10
==> Downloading https://homebrew.bintray.com/bottles/postgresql@10-10.6.mojave.bottle.tar.gz
######################################################################## 100.0%
==> Pouring postgresql@10-10.6.mojave.bottle.tar.gz
==> Caveats
To migrate existing data from a previous major version of PostgreSQL run:
  brew postgresql-upgrade-database

postgresql@10 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@10 first in your PATH run:
  echo 'export PATH="/usr/local/opt/postgresql@10/bin:$PATH"' >> ~/.zshrc

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

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


To have launchd start postgresql@10 now and restart at login:
  brew services start postgresql@10
Or, if you don't want/need a background service you can just run:
  pg_ctl -D /usr/local/var/postgres@10 start
==> Summary
🍺  /usr/local/Cellar/postgresql@10/10.6: 1,706 files, 20.8MB
==> Upgrading postgresql data from 10 to 11...
Stopping `postgresql`... (might take a while)
==> Successfully stopped `postgresql` (label: homebrew.mxcl.postgresql)
==> Moving postgresql data from /usr/local/var/postgres to /usr/local/var/postgres.old...
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 "en_US.UTF-8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

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:

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

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
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 10 to 11!
==> Your postgresql 10 data remains at /usr/local/var/postgres.old
==> Successfully started `postgresql` (label: homebrew.mxcl.postgresql)
```

:ok: :ok: :ok: っていっぱい出てるので、なんか直ってそうですね ☺️

もう一回 Rails サーバーを立ち上げなおしてみると、今度はうまくいきました ;)

![Kobito.lE1geG.png](https://qiita-image-store.s3.amazonaws.com/0/1857/1acea901-346d-c2d2-e14a-98b9b5c4b433.png "Kobito.lE1geG.png")

いかがだったでしょうか? 😆 他にも様々なデバッグ方法があるかなと思いますが、1つの考え方のご参考になれば嬉しいです (＞人＜ )✨