tmtm / ruby-mysql

MySQL connector for Ruby. pure Ruby version.
MIT License
143 stars 34 forks source link

Protocol.authenticate expects @charset to be defined #30

Open slowjoe007 opened 7 years ago

slowjoe007 commented 7 years ago

If an error occurs during authentication (in my case the host I connect from is not permitted), the error message is attempted to be decoded. However, at that time @charset is not yet defined:

Uncaught exception: undefined method `encoding' for nil:NilClass
    C:/Ruby/2.3.0/lib/ruby/gems/2.3.0/gems/ruby-mysql-2.9.14/lib/mysql/protocol.rb:502:in `read'
    C:/Ruby/2.3.0/lib/ruby/gems/2.3.0/gems/ruby-mysql-2.9.14/lib/mysql/protocol.rb:178:in `authenticate'
    C:/Ruby/2.3.0/lib/ruby/gems/2.3.0/gems/ruby-mysql-2.9.14/lib/mysql.rb:116:in `connect'
    C:/Ruby/2.3.0/lib/ruby/gems/2.3.0/gems/ruby-mysql-2.9.14/lib/mysql.rb:50:in `new'

https://github.com/tmtm/ruby-mysql/blob/44520a12fac454a41a3759256f42fea04f0032d3/lib/mysql/protocol.rb#L502

As you can see from the stacktrace the line in method authenticate is 178. However, @charset is not defined before line 185: https://github.com/tmtm/ruby-mysql/blob/44520a12fac454a41a3759256f42fea04f0032d3/lib/mysql/protocol.rb#L178-L189

I was able to help myself by modifying line 502 to:

message.force_encoding(Mysql::Charset.by_number(33).encoding)

where 33 is the numeric representation of UTF-8: https://github.com/tmtm/ruby-mysql/blob/44520a12fac454a41a3759256f42fea04f0032d3/lib/mysql/charset.rb#L63