Search code examples
ruby-on-railsdatabasepostgresqlmigrationrails-activerecord

How do I enable an extension only if it doesn't already exist?


I’m using Rails 4.2.7. I want to create a migration that enables an extension, but only if that extension doesn’t exist in the host environment in which I’m running. I have created

class EnableUuidOsspExtension < ActiveRecord::Migration
  def change
    enable_extension 'uuid-ossp'
  end
end

but I would like to suppress enabling of the extension if this is already enabled. How do I adjust the above migration to achieve this? The motivation for this is because on my local machine I have to run this to add it to PostGres, but if I migrate to Heroku, this extension may already be in place but I don’t want things to crash when I run my db migration scripts.


Solution

  • There is an extensions method that returns an array of extension names so you could do something like this:

    def up
      enable_extension('uuid-ossp') unless extensions.include?('uuid-ossp')
    end
    
    def down
      disable_extension('uuid-ossp') if extensions.include?('uuid-ossp')
    end
    

    You could also do it by hand in SQL where you'd have access to create extension if not exists:

    def up
      connection.execute('create extension if not exists "uuid-ossp"')
    end