Posts Tagged ‘yaml’

all-number passwords in database.yml

Friday, November 30th, 2007

A small posting in english, as it might help a lot of people.

When using Ruby on Rails, if you keep getting a “could not connect to database” while you are 100% sure the username and password you entered in your database.yml is correct, and you can’t find what is causing it… observe

Database.yml:

production:
  username: dontcare
  password: 0123456
  host: localhost
  ...

When we connect to the database using the RoR console, we get the following:

$ RAILS_ENV=production script/console 
Loading production environment.
>> ActiveRecord::Base.establish_connection
=> #<activerecord ::Base::ConnectionSpecification:0x40b0c0a4 @adapter_method="mysql_connection", 
@config={:host=>"localhost", :username=>"dontcare", :database=>"foobar", 
:adapter=>"mysql", :password=>42798}>
</activerecord>

(wrapped the output so it would be readable)

Take a close look to the last field in the output, the password has changed from “0123456″ to “42798″. This is, however, expected behavior, as a leading zero is interpreted as the sign the number following the zero is a octal representation of a number. This has even nothing to do with rails, this is default ruby:

$ irb
irb(main):001:0> a = 0123
=> 83

The solution is to quote your password:

production:
  username: dontcare
  password: '0123456'
  host: localhost
  ...

By the way, remember these two lines, they help you test the database connection; you can even omit the first one, but then you won’t see the actual connection parameters, which helped me discover the cause of this problem.

ActiveRecord::Base.establish_connection
ActiveRecord::Base.connection.select_all('SHOW TABLES')

Just start a console, and use these to test your database.