adding to my migration helper

Recently I added few methods to my migration helpers for the reasons

  1. Rails support for many databases causes not to have foreign key support, which I wanted to have
  2. Why to use default SIGNED column for id or for other column where it is not needed, so getting more numbers store
  3. One may not want to have unicode support for system managed tables(with no user generated content), unicode table requires more space.

I tested below units against mysql 5.1 only

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# migration_helpers.rb
module MigrationHelpers

  def add_foreign_key(from_table, from_column, to_table, to_column='id')
    constraint_name = "fk_#{from_table}_#{from_column}"
    #execute %{alter table #{from_table} add index (#{from_column})}
    add_index from_table, from_column
    execute %{alter table #{from_table} add constraint #{constraint_name} foreign key (#{from_column}) references #{to_table}(#{to_column}) ON DELETE NO ACTION ON UPDATE NO ACTION}
  end

  def remove_foreign_key(from_table, from_column)
    constraint_name = "fk_#{from_table}_#{from_column}"
    execute %{alter table #{from_table} drop foreign key #{constraint_name}}
    #execute %{alter table #{from_table} drop index index_on_#{from_table}_on_#{from_column}} # column needs to be dropped first
  end

  def innodb_latin
    'ENGINE = InnoDB DEFAULT CHARACTER SET = latin1'
  end

  def id_column
    'INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (id)'
  end

  def foreign_key_column
    'INT UNSIGNED'
  end

  def count_coulmn
    'INT UNSIGNED DEFAULT 0'
  end

  def number_column
    'INT UNSIGNED'
  end
end

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class CreateAuthentications < ActiveRecord::Migration
  def self.up
    create_table :authentications, :id => false, :options => innodb_latin do |t|
      t.column      :id, id_column
      t.column      :user_id, foreign_key_column
      t.string      :provider
      t.string      :uid
      t.text        :user_data
      t.timestamps
    end
  end

  def self.down
    drop_table :authentications
  end
end

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s