Fixing mysql2 installation for Homebrew MySQL



Homebrew is a popular package manager to install local dependencies on macOS. Bundler is an application application package manager for Ruby and allows you to install different dependency versions per application environment. mysql2 is a Ruby package/gem for managing connections to MySQL.

Dependending on your setup, the default mysql path by Homebrew may not necessarily match the default path used by bundler. When running bundle install, you will see the following error:

Using devise 4.8.1
Installing mysql2 0.5.3 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native

current directory:
/Users/foo/.rbenv/versions/3.0.3/bin/ruby -I
/Users/foo/.rbenv/versions/3.0.3/lib/ruby/3.0.0 -r
./siteconf20220103-55703-1aark7.rb extconf.rb
checking for rb_absint_size()... yes
checking for rb_absint_singlebit_p()... yes
checking for rb_wait_for_single_fd()... yes
Using mysql_config at /usr/local/bin/mysql_config

The default installation path of homebrew mysql libs are not discovered by mysql2: Don't know how to set rpath on your system, if MySQL libraries are not in path mysql2 may not load

How to Fix

  1. Check current mysql installation path:

     ➜  demo git:(main) which mysql
     ➜  demo git:(main) ls -l /usr/local/bin/mysql
     lrwxr-xr-x  1 foo  admin  34 Jan  3 14:56 /usr/local/bin/mysql -> ../Cellar/mysql/8.0.27_1/bin/mysql

    i.e. /usr/local/Cellar/mysql/

  2. Set local mysql build paths:

     bundle config --local build.mysql2 "--with-mysql-lib=/usr/local/Cellar/mysql/8.0.27_1/lib --with-mysql-dir=/usr/local/Cellar/mysql/8.0.27_1 --with-mysql-config=/usr/local/Cellar/mysql/8.0.27_1/bin/mysql_config  --with-mysql-include=/usr/local/Cellar/mysql/8.0.27_1/include"
  3. Re-run bundle install:

     Installing mysql2 0.5.3 with native extensions
     Bundle complete! 21 Gemfile dependencies, 78 gems now installed.
     Use `bundle info [gemname]` to see where a bundled gem is installed.