Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

There was a problem

You must be a member of this account.

This project is archived and is in readonly mode.

Add column and index query methods to ActiveRecord::Schema

#4219

The attached patch adds two methods to the ActiveRecord::Schema format - column_exists? and index_exists?

The use case for this feature is to make it easier for plugin/engine developers to create migrations that can cope with a database in an indeterminate state. e.g:

class MyEngineCreateUsers < ActiveRecord::Migration
  def self.up
    if table_exists?(:users)
      # Traditional style
      add_column(:users, :remember_token, :string, :limit => 128) unless column_exists?(:users, :remember_token)
      add_index(:users, :remember_token) unless index_exists?(:users, :remember_token)

      # Sexy style
      change_table(:users) do |t|
        t.string(:confirmation_token, :limit => 128) unless t.column_exists?(:confirmation_token)
        t.boolean(:email_confirmed, :default => false, :null => false) unless t.column_exists?(:email_confirmed)
        t.index([:id, :confirmation_token]) unless t.index_exists?([:id, :confirmation_token])
      end
    else
      create_table(:users) do |t|
        t.string   :email
        t.string   :encrypted_password, :limit => 128
        t.string   :salt,               :limit => 128
        t.string   :confirmation_token, :limit => 128
        t.string   :remember_token,     :limit => 128
        t.boolean  :email_confirmed, :default => false, :null => false
        t.timestamps
      end

      add_index :users, [:id, :confirmation_token]
      add_index :users, :email
      add_index :users, :remember_token
    end
  end

  def self.down
    drop_table :users
  end
end

Reported by Andrew White · March 18th, 2010 @ 05:21 PM

State: resolved
Milestone: 3.0.2
Assigned to: José Valim José Valim
Importance: Low

Activity

  1. Andrew White
    Andrew White

    Updated patch.

    I've had to rename the index_exists? method from #3452 [PATCH] Improve DB index handling as it clashed with this patch. The index_exists? from #3452 [PATCH] Improve DB index handling only supports checking by index name and is a support method whereas my index_exists? is more for using within migrations.

    I did a quick survey of all of the AR adapters I could find and all of the ones for SQL databases define an indexes method. The only ones that didn't were for NoSQL databases or even more esoteric situations like a null/no-op database for testing.

    June 9th, 2010 @ 11:49 AM

  2. Andrew White
    Andrew White
    • Milestone cleared.
    • State changed from new to open
    • Assigned user set to José Valim

    June 25th, 2010 @ 05:53 PM

  3. Repository
  4. Jeremy Kemper
    Jeremy Kemper
    • Milestone set to 3.0.2
    • Importance changed from to Low

    October 15th, 2010 @ 11:01 PM