数据库连接错误 – PG :: ConnectionBad:无法连接到服务器:没有这样的文件或目录

1. 环境

macOS 10.15.7 卡塔里娜版
Ruby 2.6.5p114
Rails 6.0.3.7

首先

我遇到了错误,自己查找并解决了,但为了将来再次发生时保留一份备份。
同时,希望能对遇到相同错误困扰的人提供帮助。

3. 错误信息

在进行设备的引入,并执行rails db:migrate命令时。

kanta@fukazawakantanoMacBook-Pro insta-app-daytra % rails db:migrate
rails aborted!
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"?

看起来是关于数据库连接方面的错误。

4、我做过的实验

使用DeepL将错误消息翻译为中文。

PG::ConnectionBad:无法连接到服务器。没有此文件或目录
服务器在本地运行,并接受以下内容。
是否在Unix域套接字“/tmp/.s.PGSQL.5432”上接受连接?

ちょっと意味は分かったけど、根本的な問題が分からない。
因此无法理解错误信息。

服务器是否正在本地运行,并在Unix域套接字“/tmp/.s.PGSQL.5432”上接受连接?

如果在谷歌上搜索,则会出现以下文章。
→https://qiita.com/knxrvb/items/72d88fe5364561214e52

在终端上尝试执行那段代码来启动数据库。

postgres -D /usr/local/var/postgres

2021-05-11 15:22:39.356 JST [31540] FATAL:  database files are incompatible with server
2021-05-11 15:22:39.356 JST [31540] DETAIL:  The data directory was initialized by PostgreSQL version 12, which is not compatible with this version 13.2.
 

日志被显示出来。

数据库文件与服务器不兼容。
数据目录是使用PostgreSQL版本12初始化的,与此版本13.2不兼容。

说起来,Postgres的版本好像有点旧。
执行了文章中提到的升级代码。

brew postgresql-upgrade-database

有各种代码运行了起来,

==> brew install postgresql@12
==> Downloading https://ghcr.io/v2/homebrew/core/postgresql/12/manifests/12.6_2
######################################################################## 100.0%
     ・
   ・
   ・

虽然一开始看起来有些困难,

Error: Upgrading postgresql data from 12 to 13 failed!
==> Removing empty postgresql initdb database...
==> Moving postgresql data back from /usr/local/var/postgres.old to /usr/local/var/postgres...
Error: Failure while executing; `/usr/local/opt/postgresql/bin/pg_upgrade -r -b /usr/local/Cellar/postgresql@12/12.6_2/bin -B /usr/local/opt/postgresql/bin -d /usr/local/var/postgres.old -D /usr/local/var/postgres -j 4` exited with 1.

无法进行升级…

直接翻訳すると「そのままエラー文の」とは意味がわかりませんので、下記の日本語の文章を中国語に翻訳します。

“将错误消息保持原样”

将 PostgreSQL 数据从 12 升级到 13 失败了!

当你用谷歌搜索时,
→https://twin-t.com/postgressql%E3%82%92%E3%82%A2%E3%83%83%E3%83%97%E3%83%87%E3%83%BC%E3%83%88%E3%81%99%E3%82%8B%E9%9A%9B%E3%81%AE%E3%82%A8%E3%83%A9%E3%83%BC/
结果显示有。

似乎在启动PostgresSQL的同时进行更新可能是个错误。

请按照文中的指示,停止PostgresSQL数据库。

brew services stop postgresql
brew postgresql-upgrade-database
  .
  . 
  .
==> Upgraded postgresql data from 12 to 13!
==> Your postgresql 12 data remains at /usr/local/var/postgres.old

升级成功!试着启动数据库,

brew services start postgresql
==> Successfully started `postgresql` (label: homebrew.mxcl.postgresql)

真棒啊!

成功执行了rails db:migrate!!!

bannerAds