Search code examples
sqlruby-on-railsdeploymentrakeproduction-environment

rake db:migrate securely on staging and production environments


I enjoy using rake to manage my migrations in the development environment, where I have allowed my rails app full permissions on the dev DB.

However, in the staging and production environments, my application only has write access, not the ability to alter tables.

I'd like to continue using rake db:migrate in staging and production, but the problem is that rake db uses the same user as my rails app, which doesn't have sufficient privileges.

Does anyone know an easy way around this problem, without having to allow administrative db privileges in my rails app.

Eg, if I could specify -username and -password when I run rake db, that would be great.


Solution

  • You could specify some migration connection in your config/database.yml with a user/pass for the properly-privileged user and run

    RAILS_ENV=migration rake db:migrate
    

    Edit It looks like something like this might work (though I've never tested it over a remote connection, only locally). Add the following to your config/database.yml.

    <%
    require 'highline/import'
    
    def request_input(msg, show_input = true)
      ask(msg) { |q| q.echo = show_input }
    end
    %>
    
    migration:
      # Other connection information here (host, adapter, etc..)
      username: <%= request_input "Username:" %> 
      password: <%= request_input "Password:", false %> 
    

    When you run

    RAILS_ENV=migration rake db:migrate
    

    You will be prompted to enter the username and password for the connection. Make sure to add

    gem 'highline'
    

    to your Gemfile.

    Source: http://dzone.com/snippets/request-database