当无法在Rails中连接到数据库时,在此提供一种思考方式
我想在启动Rails服务器后无法连接到数据库的情况会偶尔发生,你们在这种情况下通常会怎么处理呢??? 我想有一种方式是通过搜索错误消息来尝试各种方法,还有一种方式是用内心来进行调试。
根据每个人的情况和环境,应采取的行动可能不同,但我通常会选择“尽量追踪官方信息来解决问题”。我认为有很多不同的方法都很好,希望这个方法能够给你一些参考(>人< )✨
「出现了某种错误!」然后进行原因调查和对策举例。
本次我将以我实际遇到的例子为基础,从遇到错误的地方开始,逐一调查原因,并最终解决问题的流程一一总结起来。顺便提一下,本次的題材是这个Rails应用程序。
CoderDojo Japan – 为儿童提供的编程训练场所
https://coderdojo.jp/
GitHub – coderdojo-japan/coderdojo.jp (OSS)
https://github.com/coderdojo-japan/coderdojo.jp
GitHub – coderdojo-japan/coderdojo.jp(开源软件)
https://github.com/coderdojo-japan/coderdojo.jp

首先要从遇到错误开始。
错误的遭遇
╭─○ 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 是否正在运行。
查询PostgreSQL的当前状态
╭─○ 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.
当调查了状态后,我发现本次情况是因为“数据库版本不同会导致无法正常运行(变得不兼容)”这个原因。原来如此!我记得最近执行过brew update和brew upgrade,所以可能是它们导致的。
升级版本时我通常使用Homebrew,并通过Homebrew访问官方信息,可以找到一些不错的信息(官方信息通常包含简洁明了的回答,给人留下了良好的印象)??
通过Homebrew,访问官方信息的方法
╭─○ 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)
我找到了一个很好的回答!到这个地步,就好像变成了“赢了 (完)”的感觉,但我们要保持警惕,按照官方信息做出应对。
请注意:按照公式信息进行适当调整很可能修复问题,但在更复杂的环境中可能不只有一个原因。在这种情况下,按照上述方式,逐个查看公式信息并进行处理似乎是个不错的方法。
按照公式信息进行处理。
╭─○ 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)
因为有很多冒泡出来,所以看起来好像修好了呢 ☺️
当我尝试重新启动Rails服务器时,这次顺利了;)

你觉得怎么样呢?? 我觉得还有其他很多调试方法,但如果能对你提供一个思路的参考,我会很高兴的 (>人< )✨