RubyRedGrapefruit
RubyRedGrapefruit

Reputation: 12224

Rails/Postgres brittle test environment not creating correct datatypes

I'm using the citext extension because of Postgres's shortcoming with respect to not having a global feature to allow case-insensitive searching.

However, in my Rails 3.2 application when I run:

rake db:test:prepare

my objects are created with text datatypes, instead of citext. How can I force the above rake command to create the database and add the extensions that my application requires in order to do the kind of searching that should just be baked in already?

Upvotes: 0

Views: 166

Answers (1)

boulder
boulder

Reputation: 3266

You need to add the citext extension to your test database. Unfortunately, in the standard implementation of db:test:prepare the database is dropped and recreated, so the extension is gone.

I found myself in the same situation and had to resort to override db:test:purge (which is called prior to prepare) with my own implementation so instead of dropping the database it would just drop the objects (a solution based on 'DROP OWNED BY username').

UPDATE with rake task code: So my rake task looks like this. I put it on lib/tasks/overrides/database.rake; but that's up to you.

 namespace :db do  
   namespace :test do
     task :purge => []
     Rake::Task["purge"].clear

     # desc overrides default task to drop all objects in database instead of the db itself (only postgresql)
     task :purge => [:environment, :load_config] do
       abcs = ActiveRecord::Base.configurations
       case abcs['test']['adapter']
         when /postgresql/
           # original implementation commented out
           #ActiveRecord::Base.clear_active_connections!
           #drop_database(abcs['test'])
           #create_database(abcs['test'])
           drop_database_objects(abcs['test'])
       end
     end
   end
 end

 def drop_database_objects(config)
   case config['adapter']
   when /postgresql/
     ActiveRecord::Base.establish_connection(config)
     sql = "DROP OWNED BY #{config['username']}"
     ActiveRecord::Base.connection.execute sql 
   end 
 end

I am omitting the parts that haven't changed, but you can see the original at database.rake. A note: I found that Postgresql 9.2.2 has a problem with the DROP OWNED BY, you'll be fine using 9.2.1 and 9.2.3; it's just that one version.

Upvotes: 1

Related Questions