Froze rails gems
[depot.git] / vendor / rails / activerecord / lib / active_record / migration.rb
1 module ActiveRecord
2 class IrreversibleMigration < ActiveRecordError#:nodoc:
3 end
4
5 class DuplicateMigrationVersionError < ActiveRecordError#:nodoc:
6 def initialize(version)
7 super("Multiple migrations have the version number #{version}")
8 end
9 end
10
11 class DuplicateMigrationNameError < ActiveRecordError#:nodoc:
12 def initialize(name)
13 super("Multiple migrations have the name #{name}")
14 end
15 end
16
17 class UnknownMigrationVersionError < ActiveRecordError #:nodoc:
18 def initialize(version)
19 super("No migration with version number #{version}")
20 end
21 end
22
23 class IllegalMigrationNameError < ActiveRecordError#:nodoc:
24 def initialize(name)
25 super("Illegal name for migration file: #{name}\n\t(only lower case letters, numbers, and '_' allowed)")
26 end
27 end
28
29 # Migrations can manage the evolution of a schema used by several physical databases. It's a solution
30 # to the common problem of adding a field to make a new feature work in your local database, but being unsure of how to
31 # push that change to other developers and to the production server. With migrations, you can describe the transformations
32 # in self-contained classes that can be checked into version control systems and executed against another database that
33 # might be one, two, or five versions behind.
34 #
35 # Example of a simple migration:
36 #
37 # class AddSsl < ActiveRecord::Migration
38 # def self.up
39 # add_column :accounts, :ssl_enabled, :boolean, :default => 1
40 # end
41 #
42 # def self.down
43 # remove_column :accounts, :ssl_enabled
44 # end
45 # end
46 #
47 # This migration will add a boolean flag to the accounts table and remove it if you're backing out of the migration.
48 # It shows how all migrations have two class methods +up+ and +down+ that describes the transformations required to implement
49 # or remove the migration. These methods can consist of both the migration specific methods like add_column and remove_column,
50 # but may also contain regular Ruby code for generating data needed for the transformations.
51 #
52 # Example of a more complex migration that also needs to initialize data:
53 #
54 # class AddSystemSettings < ActiveRecord::Migration
55 # def self.up
56 # create_table :system_settings do |t|
57 # t.string :name
58 # t.string :label
59 # t.text :value
60 # t.string :type
61 # t.integer :position
62 # end
63 #
64 # SystemSetting.create :name => "notice", :label => "Use notice?", :value => 1
65 # end
66 #
67 # def self.down
68 # drop_table :system_settings
69 # end
70 # end
71 #
72 # This migration first adds the system_settings table, then creates the very first row in it using the Active Record model
73 # that relies on the table. It also uses the more advanced create_table syntax where you can specify a complete table schema
74 # in one block call.
75 #
76 # == Available transformations
77 #
78 # * <tt>create_table(name, options)</tt> Creates a table called +name+ and makes the table object available to a block
79 # that can then add columns to it, following the same format as add_column. See example above. The options hash is for
80 # fragments like "DEFAULT CHARSET=UTF-8" that are appended to the create table definition.
81 # * <tt>drop_table(name)</tt>: Drops the table called +name+.
82 # * <tt>rename_table(old_name, new_name)</tt>: Renames the table called +old_name+ to +new_name+.
83 # * <tt>add_column(table_name, column_name, type, options)</tt>: Adds a new column to the table called +table_name+
84 # named +column_name+ specified to be one of the following types:
85 # <tt>:string</tt>, <tt>:text</tt>, <tt>:integer</tt>, <tt>:float</tt>, <tt>:decimal</tt>, <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>,
86 # <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>. A default value can be specified by passing an
87 # +options+ hash like <tt>{ :default => 11 }</tt>. Other options include <tt>:limit</tt> and <tt>:null</tt> (e.g. <tt>{ :limit => 50, :null => false }</tt>)
88 # -- see ActiveRecord::ConnectionAdapters::TableDefinition#column for details.
89 # * <tt>rename_column(table_name, column_name, new_column_name)</tt>: Renames a column but keeps the type and content.
90 # * <tt>change_column(table_name, column_name, type, options)</tt>: Changes the column to a different type using the same
91 # parameters as add_column.
92 # * <tt>remove_column(table_name, column_name)</tt>: Removes the column named +column_name+ from the table called +table_name+.
93 # * <tt>add_index(table_name, column_names, options)</tt>: Adds a new index with the name of the column. Other options include
94 # <tt>:name</tt> and <tt>:unique</tt> (e.g. <tt>{ :name => "users_name_index", :unique => true }</tt>).
95 # * <tt>remove_index(table_name, index_name)</tt>: Removes the index specified by +index_name+.
96 #
97 # == Irreversible transformations
98 #
99 # Some transformations are destructive in a manner that cannot be reversed. Migrations of that kind should raise
100 # an <tt>ActiveRecord::IrreversibleMigration</tt> exception in their +down+ method.
101 #
102 # == Running migrations from within Rails
103 #
104 # The Rails package has several tools to help create and apply migrations.
105 #
106 # To generate a new migration, you can use
107 # script/generate migration MyNewMigration
108 #
109 # where MyNewMigration is the name of your migration. The generator will
110 # create an empty migration file <tt>nnn_my_new_migration.rb</tt> in the <tt>db/migrate/</tt>
111 # directory where <tt>nnn</tt> is the next largest migration number.
112 #
113 # You may then edit the <tt>self.up</tt> and <tt>self.down</tt> methods of
114 # MyNewMigration.
115 #
116 # There is a special syntactic shortcut to generate migrations that add fields to a table.
117 # script/generate migration add_fieldname_to_tablename fieldname:string
118 #
119 # This will generate the file <tt>nnn_add_fieldname_to_tablename</tt>, which will look like this:
120 # class AddFieldnameToTablename < ActiveRecord::Migration
121 # def self.up
122 # add_column :tablenames, :fieldname, :string
123 # end
124 #
125 # def self.down
126 # remove_column :tablenames, :fieldname
127 # end
128 # end
129 #
130 # To run migrations against the currently configured database, use
131 # <tt>rake db:migrate</tt>. This will update the database by running all of the
132 # pending migrations, creating the <tt>schema_migrations</tt> table
133 # (see "About the schema_migrations table" section below) if missing.
134 #
135 # To roll the database back to a previous migration version, use
136 # <tt>rake db:migrate VERSION=X</tt> where <tt>X</tt> is the version to which
137 # you wish to downgrade. If any of the migrations throw an
138 # <tt>ActiveRecord::IrreversibleMigration</tt> exception, that step will fail and you'll
139 # have some manual work to do.
140 #
141 # == Database support
142 #
143 # Migrations are currently supported in MySQL, PostgreSQL, SQLite,
144 # SQL Server, Sybase, and Oracle (all supported databases except DB2).
145 #
146 # == More examples
147 #
148 # Not all migrations change the schema. Some just fix the data:
149 #
150 # class RemoveEmptyTags < ActiveRecord::Migration
151 # def self.up
152 # Tag.find(:all).each { |tag| tag.destroy if tag.pages.empty? }
153 # end
154 #
155 # def self.down
156 # # not much we can do to restore deleted data
157 # raise ActiveRecord::IrreversibleMigration, "Can't recover the deleted tags"
158 # end
159 # end
160 #
161 # Others remove columns when they migrate up instead of down:
162 #
163 # class RemoveUnnecessaryItemAttributes < ActiveRecord::Migration
164 # def self.up
165 # remove_column :items, :incomplete_items_count
166 # remove_column :items, :completed_items_count
167 # end
168 #
169 # def self.down
170 # add_column :items, :incomplete_items_count
171 # add_column :items, :completed_items_count
172 # end
173 # end
174 #
175 # And sometimes you need to do something in SQL not abstracted directly by migrations:
176 #
177 # class MakeJoinUnique < ActiveRecord::Migration
178 # def self.up
179 # execute "ALTER TABLE `pages_linked_pages` ADD UNIQUE `page_id_linked_page_id` (`page_id`,`linked_page_id`)"
180 # end
181 #
182 # def self.down
183 # execute "ALTER TABLE `pages_linked_pages` DROP INDEX `page_id_linked_page_id`"
184 # end
185 # end
186 #
187 # == Using a model after changing its table
188 #
189 # Sometimes you'll want to add a column in a migration and populate it immediately after. In that case, you'll need
190 # to make a call to Base#reset_column_information in order to ensure that the model has the latest column data from
191 # after the new column was added. Example:
192 #
193 # class AddPeopleSalary < ActiveRecord::Migration
194 # def self.up
195 # add_column :people, :salary, :integer
196 # Person.reset_column_information
197 # Person.find(:all).each do |p|
198 # p.update_attribute :salary, SalaryCalculator.compute(p)
199 # end
200 # end
201 # end
202 #
203 # == Controlling verbosity
204 #
205 # By default, migrations will describe the actions they are taking, writing
206 # them to the console as they happen, along with benchmarks describing how
207 # long each step took.
208 #
209 # You can quiet them down by setting ActiveRecord::Migration.verbose = false.
210 #
211 # You can also insert your own messages and benchmarks by using the +say_with_time+
212 # method:
213 #
214 # def self.up
215 # ...
216 # say_with_time "Updating salaries..." do
217 # Person.find(:all).each do |p|
218 # p.update_attribute :salary, SalaryCalculator.compute(p)
219 # end
220 # end
221 # ...
222 # end
223 #
224 # The phrase "Updating salaries..." would then be printed, along with the
225 # benchmark for the block when the block completes.
226 #
227 # == About the schema_migrations table
228 #
229 # Rails versions 2.0 and prior used to create a table called
230 # <tt>schema_info</tt> when using migrations. This table contained the
231 # version of the schema as of the last applied migration.
232 #
233 # Starting with Rails 2.1, the <tt>schema_info</tt> table is
234 # (automatically) replaced by the <tt>schema_migrations</tt> table, which
235 # contains the version numbers of all the migrations applied.
236 #
237 # As a result, it is now possible to add migration files that are numbered
238 # lower than the current schema version: when migrating up, those
239 # never-applied "interleaved" migrations will be automatically applied, and
240 # when migrating down, never-applied "interleaved" migrations will be skipped.
241 #
242 # == Timestamped Migrations
243 #
244 # By default, Rails generates migrations that look like:
245 #
246 # 20080717013526_your_migration_name.rb
247 #
248 # The prefix is a generation timestamp (in UTC).
249 #
250 # If you'd prefer to use numeric prefixes, you can turn timestamped migrations
251 # off by setting:
252 #
253 # config.active_record.timestamped_migrations = false
254 #
255 # In environment.rb.
256 #
257 class Migration
258 @@verbose = true
259 cattr_accessor :verbose
260
261 class << self
262 def up_with_benchmarks #:nodoc:
263 migrate(:up)
264 end
265
266 def down_with_benchmarks #:nodoc:
267 migrate(:down)
268 end
269
270 # Execute this migration in the named direction
271 def migrate(direction)
272 return unless respond_to?(direction)
273
274 case direction
275 when :up then announce "migrating"
276 when :down then announce "reverting"
277 end
278
279 result = nil
280 time = Benchmark.measure { result = send("#{direction}_without_benchmarks") }
281
282 case direction
283 when :up then announce "migrated (%.4fs)" % time.real; write
284 when :down then announce "reverted (%.4fs)" % time.real; write
285 end
286
287 result
288 end
289
290 # Because the method added may do an alias_method, it can be invoked
291 # recursively. We use @ignore_new_methods as a guard to indicate whether
292 # it is safe for the call to proceed.
293 def singleton_method_added(sym) #:nodoc:
294 return if defined?(@ignore_new_methods) && @ignore_new_methods
295
296 begin
297 @ignore_new_methods = true
298
299 case sym
300 when :up, :down
301 klass = (class << self; self; end)
302 klass.send(:alias_method_chain, sym, "benchmarks")
303 end
304 ensure
305 @ignore_new_methods = false
306 end
307 end
308
309 def write(text="")
310 puts(text) if verbose
311 end
312
313 def announce(message)
314 text = "#{@version} #{name}: #{message}"
315 length = [0, 75 - text.length].max
316 write "== %s %s" % [text, "=" * length]
317 end
318
319 def say(message, subitem=false)
320 write "#{subitem ? " ->" : "--"} #{message}"
321 end
322
323 def say_with_time(message)
324 say(message)
325 result = nil
326 time = Benchmark.measure { result = yield }
327 say "%.4fs" % time.real, :subitem
328 say("#{result} rows", :subitem) if result.is_a?(Integer)
329 result
330 end
331
332 def suppress_messages
333 save, self.verbose = verbose, false
334 yield
335 ensure
336 self.verbose = save
337 end
338
339 def method_missing(method, *arguments, &block)
340 arg_list = arguments.map(&:inspect) * ', '
341
342 say_with_time "#{method}(#{arg_list})" do
343 unless arguments.empty? || method == :execute
344 arguments[0] = Migrator.proper_table_name(arguments.first)
345 end
346 ActiveRecord::Base.connection.send(method, *arguments, &block)
347 end
348 end
349 end
350 end
351
352 # MigrationProxy is used to defer loading of the actual migration classes
353 # until they are needed
354 class MigrationProxy
355
356 attr_accessor :name, :version, :filename
357
358 delegate :migrate, :announce, :write, :to=>:migration
359
360 private
361
362 def migration
363 @migration ||= load_migration
364 end
365
366 def load_migration
367 load(filename)
368 name.constantize
369 end
370
371 end
372
373 class Migrator#:nodoc:
374 class << self
375 def migrate(migrations_path, target_version = nil)
376 case
377 when target_version.nil? then up(migrations_path, target_version)
378 when current_version > target_version then down(migrations_path, target_version)
379 else up(migrations_path, target_version)
380 end
381 end
382
383 def rollback(migrations_path, steps=1)
384 migrator = self.new(:down, migrations_path)
385 start_index = migrator.migrations.index(migrator.current_migration)
386
387 return unless start_index
388
389 finish = migrator.migrations[start_index + steps]
390 down(migrations_path, finish ? finish.version : 0)
391 end
392
393 def up(migrations_path, target_version = nil)
394 self.new(:up, migrations_path, target_version).migrate
395 end
396
397 def down(migrations_path, target_version = nil)
398 self.new(:down, migrations_path, target_version).migrate
399 end
400
401 def run(direction, migrations_path, target_version)
402 self.new(direction, migrations_path, target_version).run
403 end
404
405 def schema_migrations_table_name
406 Base.table_name_prefix + 'schema_migrations' + Base.table_name_suffix
407 end
408
409 def get_all_versions
410 Base.connection.select_values("SELECT version FROM #{schema_migrations_table_name}").map(&:to_i).sort
411 end
412
413 def current_version
414 sm_table = schema_migrations_table_name
415 if Base.connection.table_exists?(sm_table)
416 get_all_versions.max || 0
417 else
418 0
419 end
420 end
421
422 def proper_table_name(name)
423 # Use the Active Record objects own table_name, or pre/suffix from ActiveRecord::Base if name is a symbol/string
424 name.table_name rescue "#{ActiveRecord::Base.table_name_prefix}#{name}#{ActiveRecord::Base.table_name_suffix}"
425 end
426 end
427
428 def initialize(direction, migrations_path, target_version = nil)
429 raise StandardError.new("This database does not yet support migrations") unless Base.connection.supports_migrations?
430 Base.connection.initialize_schema_migrations_table
431 @direction, @migrations_path, @target_version = direction, migrations_path, target_version
432 end
433
434 def current_version
435 migrated.last || 0
436 end
437
438 def current_migration
439 migrations.detect { |m| m.version == current_version }
440 end
441
442 def run
443 target = migrations.detect { |m| m.version == @target_version }
444 raise UnknownMigrationVersionError.new(@target_version) if target.nil?
445 unless (up? && migrated.include?(target.version.to_i)) || (down? && !migrated.include?(target.version.to_i))
446 target.migrate(@direction)
447 record_version_state_after_migrating(target.version)
448 end
449 end
450
451 def migrate
452 current = migrations.detect { |m| m.version == current_version }
453 target = migrations.detect { |m| m.version == @target_version }
454
455 if target.nil? && !@target_version.nil? && @target_version > 0
456 raise UnknownMigrationVersionError.new(@target_version)
457 end
458
459 start = up? ? 0 : (migrations.index(current) || 0)
460 finish = migrations.index(target) || migrations.size - 1
461 runnable = migrations[start..finish]
462
463 # skip the last migration if we're headed down, but not ALL the way down
464 runnable.pop if down? && !target.nil?
465
466 runnable.each do |migration|
467 Base.logger.info "Migrating to #{migration.name} (#{migration.version})"
468
469 # On our way up, we skip migrating the ones we've already migrated
470 next if up? && migrated.include?(migration.version.to_i)
471
472 # On our way down, we skip reverting the ones we've never migrated
473 if down? && !migrated.include?(migration.version.to_i)
474 migration.announce 'never migrated, skipping'; migration.write
475 next
476 end
477
478 begin
479 ddl_transaction do
480 migration.migrate(@direction)
481 record_version_state_after_migrating(migration.version)
482 end
483 rescue => e
484 canceled_msg = Base.connection.supports_ddl_transactions? ? "this and " : ""
485 raise StandardError, "An error has occurred, #{canceled_msg}all later migrations canceled:\n\n#{e}", e.backtrace
486 end
487 end
488 end
489
490 def migrations
491 @migrations ||= begin
492 files = Dir["#{@migrations_path}/[0-9]*_*.rb"]
493
494 migrations = files.inject([]) do |klasses, file|
495 version, name = file.scan(/([0-9]+)_([_a-z0-9]*).rb/).first
496
497 raise IllegalMigrationNameError.new(file) unless version
498 version = version.to_i
499
500 if klasses.detect { |m| m.version == version }
501 raise DuplicateMigrationVersionError.new(version)
502 end
503
504 if klasses.detect { |m| m.name == name.camelize }
505 raise DuplicateMigrationNameError.new(name.camelize)
506 end
507
508 klasses << returning(MigrationProxy.new) do |migration|
509 migration.name = name.camelize
510 migration.version = version
511 migration.filename = file
512 end
513 end
514
515 migrations = migrations.sort_by(&:version)
516 down? ? migrations.reverse : migrations
517 end
518 end
519
520 def pending_migrations
521 already_migrated = migrated
522 migrations.reject { |m| already_migrated.include?(m.version.to_i) }
523 end
524
525 def migrated
526 @migrated_versions ||= self.class.get_all_versions
527 end
528
529 private
530 def record_version_state_after_migrating(version)
531 sm_table = self.class.schema_migrations_table_name
532
533 @migrated_versions ||= []
534 if down?
535 @migrated_versions.delete(version.to_i)
536 Base.connection.update("DELETE FROM #{sm_table} WHERE version = '#{version}'")
537 else
538 @migrated_versions.push(version.to_i).sort!
539 Base.connection.insert("INSERT INTO #{sm_table} (version) VALUES ('#{version}')")
540 end
541 end
542
543 def up?
544 @direction == :up
545 end
546
547 def down?
548 @direction == :down
549 end
550
551 # Wrap the migration in a transaction only if supported by the adapter.
552 def ddl_transaction(&block)
553 if Base.connection.supports_ddl_transactions?
554 Base.transaction { block.call }
555 else
556 block.call
557 end
558 end
559 end
560 end