Search code examples
mysqlruby-on-railspostgresqlmigrationrails-migrations

Database Specific Migration Code


I'm creating an application that needs to run under multiple databases. I currently have some code in a migration that I only want run under specific databases (postgresql and mysql). Any way of setting this up? Thanks.


Solution

  • Your migration has access to a database connection in connection and the connection has an adapter_name method so you can just ask it what sort of connection it is:

    def self.up
        case connection.adapter_name
        when 'PostgreSQL'
            # Do PostgreSQL stuff
        when 'MySQL'
            # Do MySQL stuff
        else
            # Blow up and catch on fire. Or silently ignore it depending on your needs.
        end
    end
    

    I'm not sure if I have the MySQL adapter name right but the technique is sound and you can easily check the MySQL adapter name yourself.