2 class IrreversibleMigration < ActiveRecordError#:nodoc:
5 class DuplicateMigrationVersionError < ActiveRecordError#:nodoc:
6 def initialize(version)
7 super("Multiple migrations have the version number #{version}")
11 class IllegalMigrationNameError < ActiveRecordError#:nodoc:
13 super("Illegal name for migration file: #{name}\n\t(only lower case letters, numbers, and '_' allowed)")
17 # Migrations can manage the evolution of a schema used by several physical databases. It's a solution
18 # to the common problem of adding a field to make a new feature work in your local database, but being unsure of how to
19 # push that change to other developers and to the production server. With migrations, you can describe the transformations
20 # in self-contained classes that can be checked into version control systems and executed against another database that
21 # might be one, two, or five versions behind.
23 # Example of a simple migration:
25 # class AddSsl < ActiveRecord::Migration
27 # add_column :accounts, :ssl_enabled, :boolean, :default => 1
31 # remove_column :accounts, :ssl_enabled
35 # This migration will add a boolean flag to the accounts table and remove it if you're backing out of the migration.
36 # It shows how all migrations have two class methods +up+ and +down+ that describes the transformations required to implement
37 # or remove the migration. These methods can consist of both the migration specific methods like add_column and remove_column,
38 # but may also contain regular Ruby code for generating data needed for the transformations.
40 # Example of a more complex migration that also needs to initialize data:
42 # class AddSystemSettings < ActiveRecord::Migration
44 # create_table :system_settings do |t|
52 # SystemSetting.create :name => "notice", :label => "Use notice?", :value => 1
56 # drop_table :system_settings
60 # This migration first adds the system_settings table, then creates the very first row in it using the Active Record model
61 # that relies on the table. It also uses the more advanced create_table syntax where you can specify a complete table schema
64 # == Available transformations
66 # * <tt>create_table(name, options)</tt> Creates a table called +name+ and makes the table object available to a block
67 # that can then add columns to it, following the same format as add_column. See example above. The options hash is for
68 # fragments like "DEFAULT CHARSET=UTF-8" that are appended to the create table definition.
69 # * <tt>drop_table(name)</tt>: Drops the table called +name+.
70 # * <tt>rename_table(old_name, new_name)</tt>: Renames the table called +old_name+ to +new_name+.
71 # * <tt>add_column(table_name, column_name, type, options)</tt>: Adds a new column to the table called +table_name+
72 # named +column_name+ specified to be one of the following types:
73 # :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time,
74 # :date, :binary, :boolean. A default value can be specified by passing an
75 # +options+ hash like { :default => 11 }. Other options include :limit and :null (e.g. { :limit => 50, :null => false })
76 # -- see ActiveRecord::ConnectionAdapters::TableDefinition#column for details.
77 # * <tt>rename_column(table_name, column_name, new_column_name)</tt>: Renames a column but keeps the type and content.
78 # * <tt>change_column(table_name, column_name, type, options)</tt>: Changes the column to a different type using the same
79 # parameters as add_column.
80 # * <tt>remove_column(table_name, column_name)</tt>: Removes the column named +column_name+ from the table called +table_name+.
81 # * <tt>add_index(table_name, column_names, options)</tt>: Adds a new index with the name of the column. Other options include
82 # :name and :unique (e.g. { :name => "users_name_index", :unique => true }).
83 # * <tt>remove_index(table_name, index_name)</tt>: Removes the index specified by +index_name+.
85 # == Irreversible transformations
87 # Some transformations are destructive in a manner that cannot be reversed. Migrations of that kind should raise
88 # an <tt>ActiveRecord::IrreversibleMigration</tt> exception in their +down+ method.
90 # == Running migrations from within Rails
92 # The Rails package has several tools to help create and apply migrations.
94 # To generate a new migration, use <tt>script/generate migration MyNewMigration</tt>
95 # where MyNewMigration is the name of your migration. The generator will
96 # create a file <tt>nnn_my_new_migration.rb</tt> in the <tt>db/migrate/</tt>
97 # directory where <tt>nnn</tt> is the next largest migration number.
98 # You may then edit the <tt>self.up</tt> and <tt>self.down</tt> methods of
101 # To run migrations against the currently configured database, use
102 # <tt>rake db:migrate</tt>. This will update the database by running all of the
103 # pending migrations, creating the <tt>schema_info</tt> table if missing.
105 # To roll the database back to a previous migration version, use
106 # <tt>rake db:migrate VERSION=X</tt> where <tt>X</tt> is the version to which
107 # you wish to downgrade. If any of the migrations throw an
108 # <tt>ActiveRecord::IrreversibleMigration</tt> exception, that step will fail and you'll
109 # have some manual work to do.
111 # == Database support
113 # Migrations are currently supported in MySQL, PostgreSQL, SQLite,
114 # SQL Server, Sybase, and Oracle (all supported databases except DB2).
118 # Not all migrations change the schema. Some just fix the data:
120 # class RemoveEmptyTags < ActiveRecord::Migration
122 # Tag.find(:all).each { |tag| tag.destroy if tag.pages.empty? }
126 # # not much we can do to restore deleted data
127 # raise ActiveRecord::IrreversibleMigration, "Can't recover the deleted tags"
131 # Others remove columns when they migrate up instead of down:
133 # class RemoveUnnecessaryItemAttributes < ActiveRecord::Migration
135 # remove_column :items, :incomplete_items_count
136 # remove_column :items, :completed_items_count
140 # add_column :items, :incomplete_items_count
141 # add_column :items, :completed_items_count
145 # And sometimes you need to do something in SQL not abstracted directly by migrations:
147 # class MakeJoinUnique < ActiveRecord::Migration
149 # execute "ALTER TABLE `pages_linked_pages` ADD UNIQUE `page_id_linked_page_id` (`page_id`,`linked_page_id`)"
153 # execute "ALTER TABLE `pages_linked_pages` DROP INDEX `page_id_linked_page_id`"
157 # == Using a model after changing its table
159 # Sometimes you'll want to add a column in a migration and populate it immediately after. In that case, you'll need
160 # to make a call to Base#reset_column_information in order to ensure that the model has the latest column data from
161 # after the new column was added. Example:
163 # class AddPeopleSalary < ActiveRecord::Migration
165 # add_column :people, :salary, :integer
166 # Person.reset_column_information
167 # Person.find(:all).each do |p|
168 # p.update_attribute :salary, SalaryCalculator.compute(p)
173 # == Controlling verbosity
175 # By default, migrations will describe the actions they are taking, writing
176 # them to the console as they happen, along with benchmarks describing how
177 # long each step took.
179 # You can quiet them down by setting ActiveRecord::Migration.verbose = false.
181 # You can also insert your own messages and benchmarks by using the #say_with_time
186 # say_with_time "Updating salaries..." do
187 # Person.find(:all).each do |p|
188 # p.update_attribute :salary, SalaryCalculator.compute(p)
194 # The phrase "Updating salaries..." would then be printed, along with the
195 # benchmark for the block when the block completes.
198 cattr_accessor :verbose
201 def up_with_benchmarks #:nodoc:
205 def down_with_benchmarks #:nodoc:
209 # Execute this migration in the named direction
210 def migrate(direction)
211 return unless respond_to?(direction)
214 when :up then announce "migrating"
215 when :down then announce "reverting"
219 time = Benchmark.measure { result = send("#{direction}_without_benchmarks") }
222 when :up then announce "migrated (%.4fs)" % time.real; write
223 when :down then announce "reverted (%.4fs)" % time.real; write
229 # Because the method added may do an alias_method, it can be invoked
230 # recursively. We use @ignore_new_methods as a guard to indicate whether
231 # it is safe for the call to proceed.
232 def singleton_method_added(sym) #:nodoc:
233 return if @ignore_new_methods
236 @ignore_new_methods = true
240 klass = (class << self; self; end)
241 klass.send(:alias_method_chain, sym, "benchmarks")
244 @ignore_new_methods = false
249 puts(text) if verbose
252 def announce(message)
253 text = "#{@version} #{name}: #{message}"
254 length = [0, 75 - text.length].max
255 write "== %s %s" % [text, "=" * length]
258 def say(message, subitem=false)
259 write "#{subitem ? " ->" : "--"} #{message}"
262 def say_with_time(message)
265 time = Benchmark.measure { result = yield }
266 say "%.4fs" % time.real, :subitem
267 say("#{result} rows", :subitem) if result.is_a?(Integer)
271 def suppress_messages
272 save, self.verbose = verbose, false
278 def method_missing(method, *arguments, &block)
279 arg_list = arguments.map(&:inspect) * ', '
281 say_with_time "#{method}(#{arg_list})" do
282 unless arguments.empty? || method == :execute
283 arguments[0] = Migrator.proper_table_name(arguments.first)
285 ActiveRecord::Base.connection.send(method, *arguments, &block)
291 class Migrator#:nodoc:
293 def migrate(migrations_path, target_version = nil)
294 Base.connection.initialize_schema_information
297 when target_version.nil?, current_version < target_version
298 up(migrations_path, target_version)
299 when current_version > target_version
300 down(migrations_path, target_version)
301 when current_version == target_version
302 return # You're on the right version
306 def up(migrations_path, target_version = nil)
307 self.new(:up, migrations_path, target_version).migrate
310 def down(migrations_path, target_version = nil)
311 self.new(:down, migrations_path, target_version).migrate
314 def schema_info_table_name
315 Base.table_name_prefix + "schema_info" + Base.table_name_suffix
319 Base.connection.select_value("SELECT version FROM #{schema_info_table_name}").to_i
322 def proper_table_name(name)
323 # Use the ActiveRecord objects own table_name, or pre/suffix from ActiveRecord::Base if name is a symbol/string
324 name.table_name rescue "#{ActiveRecord::Base.table_name_prefix}#{name}#{ActiveRecord::Base.table_name_suffix}"
328 def initialize(direction, migrations_path, target_version = nil)
329 raise StandardError.new("This database does not yet support migrations") unless Base.connection.supports_migrations?
330 @direction, @migrations_path, @target_version = direction, migrations_path, target_version
331 Base.connection.initialize_schema_information
335 self.class.current_version
339 migration_classes.each do |migration_class|
340 if reached_target_version?(migration_class.version)
341 Base.logger.info("Reached target version: #{@target_version}")
345 next if irrelevant_migration?(migration_class.version)
347 Base.logger.info "Migrating to #{migration_class} (#{migration_class.version})"
348 migration_class.migrate(@direction)
349 set_schema_version(migration_class.version)
354 def migration_classes
355 migrations = migration_files.inject([]) do |migrations, migration_file|
357 version, name = migration_version_and_name(migration_file)
358 assert_unique_migration_version(migrations, version.to_i)
359 migrations << migration_class(name, version.to_i)
362 sorted = migrations.sort_by { |m| m.version }
363 down? ? sorted.reverse : sorted
366 def assert_unique_migration_version(migrations, version)
367 if !migrations.empty? && migrations.find { |m| m.version == version }
368 raise DuplicateMigrationVersionError.new(version)
373 files = Dir["#{@migrations_path}/[0-9]*_*.rb"].sort_by do |f|
374 m = migration_version_and_name(f)
375 raise IllegalMigrationNameError.new(f) unless m
378 down? ? files.reverse : files
381 def migration_class(migration_name, version)
382 klass = migration_name.camelize.constantize
383 class << klass; attr_accessor :version end
384 klass.version = version
388 def migration_version_and_name(migration_file)
389 return *migration_file.scan(/([0-9]+)_([_a-z0-9]*).rb/).first
392 def set_schema_version(version)
393 Base.connection.update("UPDATE #{self.class.schema_info_table_name} SET version = #{down? ? version.to_i - 1 : version.to_i}")
404 def reached_target_version?(version)
405 return false if @target_version == nil
406 (up? && version.to_i - 1 >= @target_version) || (down? && version.to_i <= @target_version)
409 def irrelevant_migration?(version)
410 (up? && version.to_i <= current_version) || (down? && version.to_i > current_version)