Ruby pg gem depends on the operating system’s compilation tools and libraries. If the operating system compilation tool and library change (such as operating system upgrade, etc.), it may cause an error that pg gem cannot access the database normally.
Recently upgraded to macOS Monterey 12.6, due to the update of the Xcode license agreement, the Rails project using pg gem cannot run normally:
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/postgresql@14/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)
Try installing the pg gem again
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:
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
Check the mkmf.log log file for errors
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.
It is confirmed that the problem is caused by the Xcode update license agreement when macOS Monterey 12.6 is upgraded.
Solution
There are two solutions:
Open Xcode, click to agree to the license agreement
Or open the Terminal terminal, run sudo xcodebuild -license to agree to the license agreement
Then reinstall the 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
Finally check that the pg gem is working when Rails starts