v-crn Code Log

主に備忘録

bundle exec rake db:やrails db:でmysql2関連エラー Segmentation fault at 0x0000000000000000

前提

経緯

DBとしてmysql2を指定したRailsプロジェクトにおいてbundle exec rake db:createrails db:migrateなどデータベース関連のコマンドを打ち込むと次のようなエラーが出ました。

$ bundle exec rake db:reset
/Users/username/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/mysql2-0.5.2/lib/mysql2/client.rb:90: [BUG] Segmentation fault at 0x0000000000000000
ruby 2.5.3p105 (2018-10-18 revision 65156) [x86_64-darwin18]

-- Crash Report log information --------------------------------------------
   See Crash Report log file under the one of following:                    
     * ~/Library/Logs/DiagnosticReports                                     
     * /Library/Logs/DiagnosticReports                                      
   for more details.                                                        
Don't forget to include the above Crash Report log file in bug reports.     

-- Control frame information -----------------------------------------------
c:0062 p:---- s:0339 e:000338 CFUNC  :connect
c:0061 p:0612 s:0327 e:000326 METHOD /Users/username/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/mysql2-0.5.2/lib/mysql2/client.rb:90 [FINISH]
c:0060 p:---- s:0313 e:000312 CFUNC  :new
c:0059 p:0104 s:0308 e:000307 METHOD /Users/username/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.3/lib/active_record/connection_adapters/mysql2_ada

......

[NOTE]
You may have encountered a bug in the Ruby interpreter or extension libraries.
Bug reports are welcome.
For details: http://www.ruby-lang.org/bugreport.html

[IMPORTANT]
Don't forget to include the Crash Report log file under
DiagnosticReports directory in bug reports.

その他、rails sコマンドでサーバーを起動させた状態でブラウザからhttp://localhost:3000にアクセスすると同様のエラーメッセージが表示されました。*1

解決方法

Gemfileを以下のように編集し、mysql2のバージョンを0.5から0.4に下げることで解決。

変更前

gem 'mysql2', '>= 0.4.4', '< 0.6.0'

変更後

gem 'mysql2', '>= 0.4.4', '< 0.5.0'

参考:rails のサーバー立ち上げようとしたらセグフォした件 - fumihumiのブログ

*1:このときエラーメッセージの行数がターミナルの表示行数を超えてしまっていたためになかなかエラー内容が把握できませんでした。VSCodeの設定で統合Terminalの表示行数をデフォルトの1000から200000に変更する(terminal.integrated.scrollback: 200000)ことでエラーメッセージ全体を表示できるようになり、「Segmentation fault」というキーワードに行き着くことができました。