[Rails FAQs] macOS 操作系统更新 Xcode 后导致 `pg` gem 无法正常访问数据库

背景

Ruby 的 pg gem 依赖于操作系统的编译工具和类库。如果操作系统编译工具和类库发生变化(如操作系统升级等),可能会导致 pg gem 无法正常访问数据库的错误。

问题

最近升级到 macOS Monterey 12.6 ,因为 Xcode 许可证协议更新,遇到使用 pg gem 的 Rails 项目无法正常运行:

1
2
3
4
5
$ rails c
~/.asdf/installs/ruby/3.0.0/lib/ruby/gems/3.0.0/gems/bootsnap-1.7.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require': dlopen(~/.asdf/installs/ruby/3.0.0/lib/ruby/gems/3.0.0/gems/pg-1.4.3/lib/pg_ext.bundle, 0x0009): Library not loaded: '/usr/local/opt/postgresql/lib/libpq.5.dylib'
Referenced from: '~/.asdf/installs/ruby/3.0.0/lib/ruby/gems/3.0.0/gems/pg-1.2.3/lib/pg_ext.bundle'
Reason: tried: '/usr/local/opt/postgresql/lib/libpq.5.dylib' (no such file), '/usr/local/lib/libpq.5.dylib' (no such file), '/usr/lib/libpq.5.dylib' (no such file), '/usr/local/Cellar/[email protected]/14.5_1/lib/libpq.5.dylib' (no such file), '/usr/local/lib/libpq.5.dylib' (no such file), '/usr/lib/libpq.5.dylib' (no such file) - ~/.asdf/installs/ruby/3.0.0/lib/ruby/gems/3.0.0/gems/pg-1.4.3/lib/pg_ext.bundle (LoadError)
...

尝试再次安装 pg gem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ gem install pg

Fetching pg-1.4.3.gem
Building native extensions. This could take a while...
ERROR: Error installing pg:
ERROR: Failed to build gem native extension.
....
To see why this extension failed to compile, please check the mkmf.log which can be found here:

~/.asdf/installs/ruby/3.0.0/lib/ruby/gems/3.0.0/extensions/x86_64-darwin-20/3.0.0/pg-1.4.3/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in ~/.asdf/installs/ruby/3.0.0/lib/ruby/gems/3.0.0/gems/pg-1.4.3 for inspection.
Results logged to ~/.asdf/installs/ruby/3.0.0/lib/ruby/gems/3.0.0/extensions/x86_64-darwin-20/3.0.0/pg-1.4.3/gem_make.out

根据错误提示检查 mkmf.log 日志文件

1
2
#  ~.asdf/installs/ruby/3.0.0/lib/ruby/gems/3.0.0/extensions/x86_64-darwin-20/3.0.0/pg-1.4.3/mkmf.log
You have not agreed to the Xcode license agreements, please run 'sudo xcodebuild -license' from within a Terminal window to review and agree to the Xcode license agreements.

确认是 macOS Monterey 12.6 升级时 Xcode 更新许可证协议导致的问题。

解决

解决办法有两个:

  • 打开 Xcode,点击 同意 许可证协议
  • 或者打开 Terminal 终端,运行 sudo xcodebuild -license 同意许可证协议

然后重新安装 pg gem

1
2
3
4
5
6
$ gem uninstall pg

$ gem install pg

# Or specify pg version
# $ gem install pg -v 1.4.3

最后检查 Rails 启动时 pg gem 是否正常工作

1
2
$ rails c
irb(main):001:0>

参考

[1] ged/ruby-pg: A PostgreSQL client library for Ruby - https://github.com/ged/ruby-pg

[2] pg | RubyGems.org | your community gem host - https://rubygems.org/gems/pg

[3] Ruby on Rails Guides - https://guides.rubyonrails.org/