migration.rb 33.7 KB
Newer Older
1
require "active_support/core_ext/module/attribute_accessors"
2
require 'set'
3

4
module ActiveRecord
5 6 7 8 9 10 11
  class MigrationError < ActiveRecordError#:nodoc:
    def initialize(message = nil)
      message = "\n\n#{message}\n\n" if message
      super
    end
  end

P
Pratik Naik 已提交
12
  # Exception that can be raised to stop migrations from going backwards.
13
  class IrreversibleMigration < MigrationError
14
  end
15

16
  class DuplicateMigrationVersionError < MigrationError#:nodoc:
17 18 19 20
    def initialize(version)
      super("Multiple migrations have the version number #{version}")
    end
  end
21

22
  class DuplicateMigrationNameError < MigrationError#:nodoc:
23 24 25 26 27
    def initialize(name)
      super("Multiple migrations have the name #{name}")
    end
  end

28
  class UnknownMigrationVersionError < MigrationError #:nodoc:
29 30 31 32 33
    def initialize(version)
      super("No migration with version number #{version}")
    end
  end

34
  class IllegalMigrationNameError < MigrationError#:nodoc:
35 36 37 38 39
    def initialize(name)
      super("Illegal name for migration file: #{name}\n\t(only lower case letters, numbers, and '_' allowed)")
    end
  end

40
  class PendingMigrationError < MigrationError#:nodoc:
S
schneems 已提交
41
    def initialize
42
      if defined?(Rails.env)
43
        super("Migrations are pending. To resolve this issue, run:\n\n\tbin/rake db:migrate RAILS_ENV=#{::Rails.env}")
44
      else
45
        super("Migrations are pending. To resolve this issue, run:\n\n\tbin/rake db:migrate")
46
      end
S
schneems 已提交
47 48 49
    end
  end

R
Rizwan Reza 已提交
50
  # = Active Record Migrations
51 52
  #
  # Migrations can manage the evolution of a schema used by several physical
R
Rizwan Reza 已提交
53 54
  # databases. It's a solution to the common problem of adding a field to make
  # a new feature work in your local database, but being unsure of how to
55
  # push that change to other developers and to the production server. With
R
Rizwan Reza 已提交
56
  # migrations, you can describe the transformations in self-contained classes
57
  # that can be checked into version control systems and executed against
R
Rizwan Reza 已提交
58
  # another database that might be one, two, or five versions behind.
59 60 61 62
  #
  # Example of a simple migration:
  #
  #   class AddSsl < ActiveRecord::Migration
63
  #     def up
64
  #       add_column :accounts, :ssl_enabled, :boolean, default: true
65
  #     end
66
  #
67
  #     def down
68 69 70 71
  #       remove_column :accounts, :ssl_enabled
  #     end
  #   end
  #
72 73
  # This migration will add a boolean flag to the accounts table and remove it
  # if you're backing out of the migration. It shows how all migrations have
74
  # two methods +up+ and +down+ that describes the transformations
R
Rizwan Reza 已提交
75
  # required to implement or remove the migration. These methods can consist
76
  # of both the migration specific methods like +add_column+ and +remove_column+,
77
  # but may also contain regular Ruby code for generating data needed for the
R
Rizwan Reza 已提交
78
  # transformations.
79 80 81 82
  #
  # Example of a more complex migration that also needs to initialize data:
  #
  #   class AddSystemSettings < ActiveRecord::Migration
83
  #     def up
84
  #       create_table :system_settings do |t|
85 86
  #         t.string  :name
  #         t.string  :label
V
Vijay Dev 已提交
87
  #         t.text    :value
88
  #         t.string  :type
V
Vijay Dev 已提交
89
  #         t.integer :position
90
  #       end
91
  #
92 93 94
  #       SystemSetting.create  name:  'notice',
  #                             label: 'Use notice?',
  #                             value: 1
95
  #     end
96
  #
97
  #     def down
98 99 100 101
  #       drop_table :system_settings
  #     end
  #   end
  #
102
  # This migration first adds the +system_settings+ table, then creates the very
R
Rizwan Reza 已提交
103
  # first row in it using the Active Record model that relies on the table. It
104
  # also uses the more advanced +create_table+ syntax where you can specify a
R
Rizwan Reza 已提交
105
  # complete table schema in one block call.
106 107 108
  #
  # == Available transformations
  #
109
  # * <tt>create_table(name, options)</tt>: Creates a table called +name+ and
R
Rizwan Reza 已提交
110
  #   makes the table object available to a block that can then add columns to it,
111
  #   following the same format as +add_column+. See example above. The options hash
112
  #   is for fragments like "DEFAULT CHARSET=UTF-8" that are appended to the create
R
Rizwan Reza 已提交
113
  #   table definition.
114
  # * <tt>drop_table(name)</tt>: Drops the table called +name+.
115
  # * <tt>change_table(name, options)</tt>: Allows to make column alterations to
116
  #   the table called +name+. It makes the table object available to a block that
117
  #   can then add/remove columns, indexes or foreign keys to it.
118
  # * <tt>rename_table(old_name, new_name)</tt>: Renames the table called +old_name+
R
Rizwan Reza 已提交
119
  #   to +new_name+.
120
  # * <tt>add_column(table_name, column_name, type, options)</tt>: Adds a new column
R
Rizwan Reza 已提交
121
  #   to the table called +table_name+
122
  #   named +column_name+ specified to be one of the following types:
123
  #   <tt>:string</tt>, <tt>:text</tt>, <tt>:integer</tt>, <tt>:float</tt>,
R
Rizwan Reza 已提交
124
  #   <tt>:decimal</tt>, <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>,
125
  #   <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>. A default value can be
126
  #   specified by passing an +options+ hash like <tt>{ default: 11 }</tt>.
127
  #   Other options include <tt>:limit</tt> and <tt>:null</tt> (e.g.
128
  #   <tt>{ limit: 50, null: false }</tt>) -- see
R
Rizwan Reza 已提交
129 130 131
  #   ActiveRecord::ConnectionAdapters::TableDefinition#column for details.
  # * <tt>rename_column(table_name, column_name, new_column_name)</tt>: Renames
  #   a column but keeps the type and content.
132
  # * <tt>change_column(table_name, column_name, type, options)</tt>:  Changes
R
Rizwan Reza 已提交
133
  #   the column to a different type using the same parameters as add_column.
134 135
  # * <tt>remove_column(table_name, column_name, type, options)</tt>: Removes the column
  #   named +column_name+ from the table called +table_name+.
136
  # * <tt>add_index(table_name, column_names, options)</tt>: Adds a new index
R
Rizwan Reza 已提交
137
  #   with the name of the column. Other options include
138
  #   <tt>:name</tt>, <tt>:unique</tt> (e.g.
139
  #   <tt>{ name: 'users_name_index', unique: true }</tt>) and <tt>:order</tt>
L
Lincoln Lee 已提交
140
  #   (e.g. <tt>{ order: { name: :desc } }</tt>).
141
  # * <tt>remove_index(table_name, column: column_name)</tt>: Removes the index
142
  #   specified by +column_name+.
143
  # * <tt>remove_index(table_name, name: index_name)</tt>: Removes the index
144
  #   specified by +index_name+.
145 146 147
  #
  # == Irreversible transformations
  #
148 149
  # Some transformations are destructive in a manner that cannot be reversed.
  # Migrations of that kind should raise an <tt>ActiveRecord::IrreversibleMigration</tt>
R
Rizwan Reza 已提交
150
  # exception in their +down+ method.
151
  #
152 153
  # == Running migrations from within Rails
  #
154 155
  # The Rails package has several tools to help create and apply migrations.
  #
156
  # To generate a new migration, you can use
157
  #   rails generate migration MyNewMigration
P
Pratik Naik 已提交
158
  #
159
  # where MyNewMigration is the name of your migration. The generator will
160 161
  # create an empty migration file <tt>timestamp_my_new_migration.rb</tt>
  # in the <tt>db/migrate/</tt> directory where <tt>timestamp</tt> is the
R
Rizwan Reza 已提交
162
  # UTC formatted date and time that the migration was generated.
P
Pratik Naik 已提交
163 164
  #
  # There is a special syntactic shortcut to generate migrations that add fields to a table.
R
Rizwan Reza 已提交
165
  #
166
  #   rails generate migration add_fieldname_to_tablename fieldname:string
P
Pratik Naik 已提交
167
  #
P
Pratik Naik 已提交
168
  # This will generate the file <tt>timestamp_add_fieldname_to_tablename</tt>, which will look like this:
P
Pratik Naik 已提交
169
  #   class AddFieldnameToTablename < ActiveRecord::Migration
170
  #     def change
171
  #       add_column :tablenames, :fieldname, :string
P
Pratik Naik 已提交
172 173
  #     end
  #   end
174
  #
175
  # To run migrations against the currently configured database, use
176
  # <tt>rake db:migrate</tt>. This will update the database by running all of the
177
  # pending migrations, creating the <tt>schema_migrations</tt> table
178
  # (see "About the schema_migrations table" section below) if missing. It will also
P
Pratik Naik 已提交
179 180
  # invoke the db:schema:dump task, which will update your db/schema.rb file
  # to match the structure of your database.
181 182
  #
  # To roll the database back to a previous migration version, use
183
  # <tt>rake db:migrate VERSION=X</tt> where <tt>X</tt> is the version to which
184 185 186
  # you wish to downgrade. Alternatively, you can also use the STEP option if you
  # wish to rollback last few migrations. <tt>rake db:migrate STEP=2</tt> will rollback
  # the latest two migrations.
187 188
  #
  # If any of the migrations throw an <tt>ActiveRecord::IrreversibleMigration</tt> exception,
189
  # that step will fail and you'll have some manual work to do.
190
  #
191 192
  # == Database support
  #
193
  # Migrations are currently supported in MySQL, PostgreSQL, SQLite,
194
  # SQL Server, and Oracle (all supported databases except DB2).
195 196 197 198 199 200
  #
  # == More examples
  #
  # Not all migrations change the schema. Some just fix the data:
  #
  #   class RemoveEmptyTags < ActiveRecord::Migration
201
  #     def up
V
Vijay Dev 已提交
202
  #       Tag.all.each { |tag| tag.destroy if tag.pages.empty? }
203
  #     end
204
  #
205
  #     def down
206
  #       # not much we can do to restore deleted data
207
  #       raise ActiveRecord::IrreversibleMigration, "Can't recover the deleted tags"
208 209 210 211 212 213
  #     end
  #   end
  #
  # Others remove columns when they migrate up instead of down:
  #
  #   class RemoveUnnecessaryItemAttributes < ActiveRecord::Migration
214
  #     def up
215 216 217 218
  #       remove_column :items, :incomplete_items_count
  #       remove_column :items, :completed_items_count
  #     end
  #
219
  #     def down
220 221 222 223
  #       add_column :items, :incomplete_items_count
  #       add_column :items, :completed_items_count
  #     end
  #   end
224
  #
D
David Heinemeier Hansson 已提交
225
  # And sometimes you need to do something in SQL not abstracted directly by migrations:
226 227
  #
  #   class MakeJoinUnique < ActiveRecord::Migration
228
  #     def up
229 230 231
  #       execute "ALTER TABLE `pages_linked_pages` ADD UNIQUE `page_id_linked_page_id` (`page_id`,`linked_page_id`)"
  #     end
  #
232
  #     def down
233 234 235
  #       execute "ALTER TABLE `pages_linked_pages` DROP INDEX `page_id_linked_page_id`"
  #     end
  #   end
236
  #
237
  # == Using a model after changing its table
238
  #
239 240 241
  # Sometimes you'll want to add a column in a migration and populate it
  # immediately after. In that case, you'll need to make a call to
  # <tt>Base#reset_column_information</tt> in order to ensure that the model has the
R
Rizwan Reza 已提交
242
  # latest column data from after the new column was added. Example:
243
  #
244
  #   class AddPeopleSalary < ActiveRecord::Migration
A
Aaron Patterson 已提交
245
  #     def up
246
  #       add_column :people, :salary, :integer
247
  #       Person.reset_column_information
V
Vijay Dev 已提交
248
  #       Person.all.each do |p|
249
  #         p.update_attribute :salary, SalaryCalculator.compute(p)
250 251
  #       end
  #     end
252
  #   end
J
Jamis Buck 已提交
253 254 255 256 257 258 259 260 261
  #
  # == Controlling verbosity
  #
  # By default, migrations will describe the actions they are taking, writing
  # them to the console as they happen, along with benchmarks describing how
  # long each step took.
  #
  # You can quiet them down by setting ActiveRecord::Migration.verbose = false.
  #
P
Pratik Naik 已提交
262
  # You can also insert your own messages and benchmarks by using the +say_with_time+
J
Jamis Buck 已提交
263 264
  # method:
  #
A
Aaron Patterson 已提交
265
  #   def up
J
Jamis Buck 已提交
266 267
  #     ...
  #     say_with_time "Updating salaries..." do
V
Vijay Dev 已提交
268
  #       Person.all.each do |p|
269
  #         p.update_attribute :salary, SalaryCalculator.compute(p)
J
Jamis Buck 已提交
270 271 272 273 274 275 276
  #       end
  #     end
  #     ...
  #   end
  #
  # The phrase "Updating salaries..." would then be printed, along with the
  # benchmark for the block when the block completes.
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
  #
  # == About the schema_migrations table
  #
  # Rails versions 2.0 and prior used to create a table called
  # <tt>schema_info</tt> when using migrations. This table contained the
  # version of the schema as of the last applied migration.
  #
  # Starting with Rails 2.1, the <tt>schema_info</tt> table is
  # (automatically) replaced by the <tt>schema_migrations</tt> table, which
  # contains the version numbers of all the migrations applied.
  #
  # As a result, it is now possible to add migration files that are numbered
  # lower than the current schema version: when migrating up, those
  # never-applied "interleaved" migrations will be automatically applied, and
  # when migrating down, never-applied "interleaved" migrations will be skipped.
292
  #
293 294 295 296 297 298 299 300 301 302 303 304
  # == Timestamped Migrations
  #
  # By default, Rails generates migrations that look like:
  #
  #    20080717013526_your_migration_name.rb
  #
  # The prefix is a generation timestamp (in UTC).
  #
  # If you'd prefer to use numeric prefixes, you can turn timestamped migrations
  # off by setting:
  #
  #    config.active_record.timestamped_migrations = false
305
  #
306
  # In application.rb.
307
  #
308 309 310 311 312 313 314 315 316 317 318 319
  # == Reversible Migrations
  #
  # Starting with Rails 3.1, you will be able to define reversible migrations.
  # Reversible migrations are migrations that know how to go +down+ for you.
  # You simply supply the +up+ logic, and the Migration system will figure out
  # how to execute the down commands for you.
  #
  # To define a reversible migration, define the +change+ method in your
  # migration like this:
  #
  #   class TenderloveMigration < ActiveRecord::Migration
  #     def change
320
  #       create_table(:horses) do |t|
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
  #         t.column :content, :text
  #         t.column :remind_at, :datetime
  #       end
  #     end
  #   end
  #
  # This migration will create the horses table for you on the way up, and
  # automatically figure out how to drop the table on the way down.
  #
  # Some commands like +remove_column+ cannot be reversed.  If you care to
  # define how to move up and down in these cases, you should define the +up+
  # and +down+ methods as before.
  #
  # If a command cannot be reversed, an
  # <tt>ActiveRecord::IrreversibleMigration</tt> exception will be raised when
  # the migration is moving down.
  #
  # For a list of commands that are reversible, please see
  # <tt>ActiveRecord::Migration::CommandRecorder</tt>.
340 341 342 343 344 345 346 347 348
  #
  # == Transactional Migrations
  #
  # If the database adapter supports DDL transactions, all migrations will
  # automatically be wrapped in a transaction. There are queries that you
  # can't execute inside a transaction though, and for these situations
  # you can turn the automatic transactions off.
  #
  #   class ChangeEnum < ActiveRecord::Migration
349 350
  #     disable_ddl_transaction!
  #
351 352 353 354 355 356 357
  #     def up
  #       execute "ALTER TYPE model_size ADD VALUE 'new_value'"
  #     end
  #   end
  #
  # Remember that you can still open your own transactions, even if you
  # are in a Migration with <tt>self.disable_ddl_transaction!</tt>.
358
  class Migration
359 360
    autoload :CommandRecorder, 'active_record/migration/command_recorder'

S
schneems 已提交
361 362 363 364

    # This class is used to verify that all migrations have been run before
    # loading a web page if config.active_record.migration_error is set to :page_load
    class CheckPending
365
      def initialize(app)
S
schneems 已提交
366
        @app = app
367
        @last_check = 0
S
schneems 已提交
368 369 370
      end

      def call(env)
371
        if connection.supports_migrations?
372 373
          mtime = ActiveRecord::Migrator.last_migration.mtime.to_i
          if @last_check < mtime
374
            ActiveRecord::Migration.check_pending!(connection)
375 376
            @last_check = mtime
          end
377
        end
378
        @app.call(env)
S
schneems 已提交
379
      end
380 381 382 383 384 385

      private

      def connection
        ActiveRecord::Base.connection
      end
S
schneems 已提交
386 387
    end

388
    class << self
389
      attr_accessor :delegate # :nodoc:
390
      attr_accessor :disable_ddl_transaction # :nodoc:
391

392 393
      def check_pending!(connection = Base.connection)
        raise ActiveRecord::PendingMigrationError if ActiveRecord::Migrator.needs_migration?(connection)
394
      end
S
schneems 已提交
395

396
      def load_schema_if_pending!
397
        if ActiveRecord::Migrator.needs_migration? || !ActiveRecord::Migrator.any_migrations?
L
Luke Hutscal 已提交
398
          # Roundtrip to Rake to allow plugins to hook into database initialization.
Y
Yves Senn 已提交
399 400 401 402 403 404 405
          FileUtils.cd Rails.root do
            current_config = Base.connection_config
            Base.clear_all_connections!
            system("bin/rake db:test:prepare")
            # Establish a new connection, the old database may be gone (db:test:prepare uses purge)
            Base.establish_connection(current_config)
          end
406 407 408 409 410 411 412 413 414 415
          check_pending!
        end
      end

      def maintain_test_schema! # :nodoc:
        if ActiveRecord::Base.maintain_test_schema
          suppress_messages { load_schema_if_pending! }
        end
      end

416 417 418
      def method_missing(name, *args, &block) # :nodoc:
        (delegate || superclass.delegate).send(name, *args, &block)
      end
419

420 421 422
      def migrate(direction)
        new.migrate direction
      end
423

424 425 426 427
      # Disable DDL transactions for this migration.
      def disable_ddl_transaction!
        @disable_ddl_transaction = true
      end
428 429 430 431 432
    end

    def disable_ddl_transaction # :nodoc:
      self.class.disable_ddl_transaction
    end
433

434
    cattr_accessor :verbose
435
    attr_accessor :name, :version
436

437 438 439
    def initialize(name = self.class.name, version = nil)
      @name       = name
      @version    = version
440
      @connection = nil
441 442
    end

443
    self.verbose = true
444 445 446
    # instantiate the delegate object after initialize is defined
    self.delegate = new

447 448
    # Reverses the migration commands for the given block and
    # the given migrations.
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
    #
    # The following migration will remove the table 'horses'
    # and create the table 'apples' on the way up, and the reverse
    # on the way down.
    #
    #   class FixTLMigration < ActiveRecord::Migration
    #     def change
    #       revert do
    #         create_table(:horses) do |t|
    #           t.text :content
    #           t.datetime :remind_at
    #         end
    #       end
    #       create_table(:apples) do |t|
    #         t.string :variety
    #       end
    #     end
    #   end
    #
468 469 470 471 472 473 474 475 476 477 478 479 480 481
    # Or equivalently, if +TenderloveMigration+ is defined as in the
    # documentation for Migration:
    #
    #   require_relative '2012121212_tenderlove_migration'
    #
    #   class FixupTLMigration < ActiveRecord::Migration
    #     def change
    #       revert TenderloveMigration
    #
    #       create_table(:apples) do |t|
    #         t.string :variety
    #       end
    #     end
    #   end
482
    #
483 484 485 486
    # This command can be nested.
    def revert(*migration_classes)
      run(*migration_classes.reverse, revert: true) unless migration_classes.empty?
      if block_given?
487 488 489 490 491 492 493 494 495 496 497 498 499
        if @connection.respond_to? :revert
          @connection.revert { yield }
        else
          recorder = CommandRecorder.new(@connection)
          @connection = recorder
          suppress_messages do
            @connection.revert { yield }
          end
          @connection = recorder.delegate
          recorder.commands.each do |cmd, args, block|
            send(cmd, *args, &block)
          end
        end
500
      end
501 502 503
    end

    def reverting?
504
      @connection.respond_to?(:reverting) && @connection.reverting
505 506
    end

507
    class ReversibleBlockHelper < Struct.new(:reverting) # :nodoc:
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
      def up
        yield unless reverting
      end

      def down
        yield if reverting
      end
    end

    # Used to specify an operation that can be run in one direction or another.
    # Call the methods +up+ and +down+ of the yielded object to run a block
    # only in one given direction.
    # The whole block will be called in the right order within the migration.
    #
    # In the following example, the looping on users will always be done
    # when the three columns 'first_name', 'last_name' and 'full_name' exist,
    # even when migrating down:
    #
    #    class SplitNameMigration < ActiveRecord::Migration
    #      def change
    #        add_column :users, :first_name, :string
    #        add_column :users, :last_name, :string
    #
    #        reversible do |dir|
    #          User.reset_column_information
    #          User.all.each do |u|
    #            dir.up   { u.first_name, u.last_name = u.full_name.split(' ') }
    #            dir.down { u.full_name = "#{u.first_name} #{u.last_name}" }
    #            u.save
    #          end
    #        end
    #
    #        revert { add_column :users, :full_name, :string }
    #      end
    #    end
    def reversible
      helper = ReversibleBlockHelper.new(reverting?)
M
Marc-Andre Lafortune 已提交
545
      execute_block{ yield helper }
546 547
    end

548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
    # Runs the given migration classes.
    # Last argument can specify options:
    # - :direction (default is :up)
    # - :revert (default is false)
    def run(*migration_classes)
      opts = migration_classes.extract_options!
      dir = opts[:direction] || :up
      dir = (dir == :down ? :up : :down) if opts[:revert]
      if reverting?
        # If in revert and going :up, say, we want to execute :down without reverting, so
        revert { run(*migration_classes, direction: dir, revert: true) }
      else
        migration_classes.each do |migration_class|
          migration_class.new.exec_migration(@connection, dir)
        end
      end
    end

566 567
    def up
      self.class.delegate = self
568
      return unless self.class.respond_to?(:up)
569 570 571 572 573
      self.class.up
    end

    def down
      self.class.delegate = self
574
      return unless self.class.respond_to?(:down)
575 576 577
      self.class.down
    end

578 579 580
    # Execute this migration in the named direction
    def migrate(direction)
      return unless respond_to?(direction)
J
Jamis Buck 已提交
581

582 583 584 585
      case direction
      when :up   then announce "migrating"
      when :down then announce "reverting"
      end
J
Jamis Buck 已提交
586

587 588
      time   = nil
      ActiveRecord::Base.connection_pool.with_connection do |conn|
589
        time = Benchmark.measure do
590
          exec_migration(conn, direction)
591
        end
592
      end
593

594 595 596
      case direction
      when :up   then announce "migrated (%.4fs)" % time.real; write
      when :down then announce "reverted (%.4fs)" % time.real; write
J
Jamis Buck 已提交
597
      end
598
    end
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613

    def exec_migration(conn, direction)
      @connection = conn
      if respond_to?(:change)
        if direction == :down
          revert { change }
        else
          change
        end
      else
        send(direction)
      end
    ensure
      @connection = nil
    end
J
Jamis Buck 已提交
614

615 616 617
    def write(text="")
      puts(text) if verbose
    end
618

619 620 621 622 623
    def announce(message)
      text = "#{version} #{name}: #{message}"
      length = [0, 75 - text.length].max
      write "== %s %s" % [text, "=" * length]
    end
J
Jamis Buck 已提交
624

625 626 627
    def say(message, subitem=false)
      write "#{subitem ? "   ->" : "--"} #{message}"
    end
J
Jamis Buck 已提交
628

629 630 631 632 633 634 635 636
    def say_with_time(message)
      say(message)
      result = nil
      time = Benchmark.measure { result = yield }
      say "%.4fs" % time.real, :subitem
      say("#{result} rows", :subitem) if result.is_a?(Integer)
      result
    end
637

638 639 640 641 642 643
    def suppress_messages
      save, self.verbose = verbose, false
      yield
    ensure
      self.verbose = save
    end
644

645
    def connection
646
      @connection || ActiveRecord::Base.connection
647
    end
648

649
    def method_missing(method, *arguments, &block)
650
      arg_list = arguments.map(&:inspect) * ', '
651 652

      say_with_time "#{method}(#{arg_list})" do
653
        unless @connection.respond_to? :revert
654
          unless arguments.empty? || [:execute, :enable_extension, :disable_extension].include?(method)
655
            arguments[0] = proper_table_name(arguments.first, table_name_options)
Y
Yves Senn 已提交
656 657 658
            if [:rename_table, :add_foreign_key].include?(method)
              arguments[1] = proper_table_name(arguments.second, table_name_options)
            end
659
          end
660
        end
661 662
        return super unless connection.respond_to?(method)
        connection.send(method, *arguments, &block)
J
Jamis Buck 已提交
663
      end
664
    end
665

666 667
    def copy(destination, sources, options = {})
      copied = []
668

A
Arun Agrawal 已提交
669
      FileUtils.mkdir_p(destination) unless File.exist?(destination)
670

671 672
      destination_migrations = ActiveRecord::Migrator.migrations(destination)
      last = destination_migrations.last
673
      sources.each do |scope, path|
674
        source_migrations = ActiveRecord::Migrator.migrations(path)
675

676
        source_migrations.each do |migration|
677 678 679 680 681 682 683 684 685 686 687
          source = File.binread(migration.filename)
          inserted_comment = "# This migration comes from #{scope} (originally #{migration.version})\n"
          if /\A#.*\b(?:en)?coding:\s*\S+/ =~ source
            # If we have a magic comment in the original migration,
            # insert our comment after the first newline(end of the magic comment line)
            # so the magic keep working.
            # Note that magic comments must be at the first line(except sh-bang).
            source[/\n/] = "\n#{inserted_comment}"
          else
            source = "#{inserted_comment}#{source}"
          end
688

689
          if duplicate = destination_migrations.detect { |m| m.name == migration.name }
690 691
            if options[:on_skip] && duplicate.scope != scope.to_s
              options[:on_skip].call(scope, migration)
692
            end
693 694
            next
          end
695

696
          migration.version = next_migration_number(last ? last.version + 1 : 0).to_i
697
          new_path = File.join(destination, "#{migration.version}_#{migration.name.underscore}.#{scope}.rb")
698 699
          old_path, migration.filename = migration.filename, new_path
          last = migration
700

701
          File.binwrite(migration.filename, source)
702
          copied << migration
703
          options[:on_copy].call(scope, migration, old_path) if options[:on_copy]
704
          destination_migrations << migration
705 706 707
        end
      end

708 709 710
      copied
    end

711 712 713 714 715 716 717 718 719 720 721
    # Finds the correct table name given an Active Record object.
    # Uses the Active Record object's own table_name, or pre/suffix from the
    # options passed in.
    def proper_table_name(name, options = {})
      if name.respond_to? :table_name
        name.table_name
      else
        "#{options[:table_name_prefix]}#{name}#{options[:table_name_suffix]}"
      end
    end

V
Vijay Dev 已提交
722
    # Determines the version number of the next migration.
723 724 725 726
    def next_migration_number(number)
      if ActiveRecord::Base.timestamped_migrations
        [Time.now.utc.strftime("%Y%m%d%H%M%S"), "%.14d" % number].max
      else
727
        SchemaMigration.normalize_migration_number(number)
728
      end
729
    end
M
Marc-Andre Lafortune 已提交
730

731 732 733 734 735 736 737
    def table_name_options(config = ActiveRecord::Base)
      {
        table_name_prefix: config.table_name_prefix,
        table_name_suffix: config.table_name_suffix
      }
    end

M
Marc-Andre Lafortune 已提交
738 739 740 741 742 743 744 745
    private
    def execute_block
      if connection.respond_to? :execute_block
        super # use normal delegation to record the block
      else
        yield
      end
    end
746 747
  end

748 749
  # MigrationProxy is used to defer loading of the actual migration classes
  # until they are needed
750
  class MigrationProxy < Struct.new(:name, :version, :filename, :scope)
751

752
    def initialize(name, version, filename, scope)
753 754 755
      super
      @migration = nil
    end
756

757 758 759 760
    def basename
      File.basename(filename)
    end

761 762 763 764
    def mtime
      File.mtime filename
    end

765
    delegate :migrate, :announce, :write, :disable_ddl_transaction, to: :migration
766 767 768 769 770 771 772 773

    private

      def migration
        @migration ||= load_migration
      end

      def load_migration
774
        require(File.expand_path(filename))
775
        name.constantize.new(name, version)
776 777 778 779
      end

  end

A
Arun Agrawal 已提交
780 781
  class NullMigration < MigrationProxy #:nodoc:
    def initialize
782 783 784 785 786 787 788 789
      super(nil, 0, nil, nil)
    end

    def mtime
      0
    end
  end

790
  class Migrator#:nodoc:
791
    class << self
792 793
      attr_writer :migrations_paths
      alias :migrations_path= :migrations_paths=
794

795
      def migrate(migrations_paths, target_version = nil, &block)
796
        case
797 798 799 800 801 802 803 804
        when target_version.nil?
          up(migrations_paths, target_version, &block)
        when current_version == 0 && target_version == 0
          []
        when current_version > target_version
          down(migrations_paths, target_version, &block)
        else
          up(migrations_paths, target_version, &block)
805 806
        end
      end
807

808 809
      def rollback(migrations_paths, steps=1)
        move(:down, migrations_paths, steps)
810
      end
811

812 813
      def forward(migrations_paths, steps=1)
        move(:up, migrations_paths, steps)
814 815
      end

816 817 818 819
      def up(migrations_paths, target_version = nil)
        migrations = migrations(migrations_paths)
        migrations.select! { |m| yield m } if block_given?

820
        new(:up, migrations, target_version).migrate
821
      end
822

823
      def down(migrations_paths, target_version = nil, &block)
824 825 826
        migrations = migrations(migrations_paths)
        migrations.select! { |m| yield m } if block_given?

827
        new(:down, migrations, target_version).migrate
828
      end
829

830
      def run(direction, migrations_paths, target_version)
831
        new(direction, migrations(migrations_paths), target_version).run
832 833 834
      end

      def open(migrations_paths)
835
        new(:up, migrations(migrations_paths), nil)
836
      end
837

838
      def schema_migrations_table_name
A
Aaron Patterson 已提交
839
        SchemaMigration.table_name
840 841
      end

842 843 844 845 846 847
      def get_all_versions(connection = Base.connection)
        if connection.table_exists?(schema_migrations_table_name)
          SchemaMigration.all.map { |x| x.version.to_i }.sort
        else
          []
        end
848 849
      end

850
      def current_version(connection = Base.connection)
851
        get_all_versions(connection).max || 0
852
      end
853

854
      def needs_migration?(connection = Base.connection)
855
        (migrations(migrations_paths).collect(&:version) - get_all_versions(connection)).size > 0
856 857
      end

858 859 860 861
      def any_migrations?
        migrations(migrations_paths).any?
      end

862
      def last_version
863 864 865
        last_migration.version
      end

A
Arun Agrawal 已提交
866
      def last_migration #:nodoc:
867
        migrations(migrations_paths).last || NullMigration.new
868 869
      end

870 871 872
      def migrations_paths
        @migrations_paths ||= ['db/migrate']
        # just to not break things if someone uses: migration_path = some_string
873
        Array(@migrations_paths)
874 875
      end

876
      def migrations_path
877
        migrations_paths.first
878 879
      end

880
      def migrations(paths)
881
        paths = Array(paths)
882

883
        files = Dir[*paths.map { |p| "#{p}/**/[0-9]*_*.rb" }]
884

A
Aaron Patterson 已提交
885
        migrations = files.map do |file|
886
          version, name, scope = file.scan(/([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?\.rb\z/).first
887 888 889

          raise IllegalMigrationNameError.new(file) unless version
          version = version.to_i
A
Aaron Patterson 已提交
890
          name = name.camelize
891

892
          MigrationProxy.new(name, version, file, scope)
893 894 895 896 897
        end

        migrations.sort_by(&:version)
      end

898 899
      private

900
      def move(direction, migrations_paths, steps)
901
        migrator = new(direction, migrations(migrations_paths))
902 903 904 905 906
        start_index = migrator.migrations.index(migrator.current_migration)

        if start_index
          finish = migrator.migrations[start_index + steps]
          version = finish ? finish.version : 0
907
          send(direction, migrations_paths, version)
908 909
        end
      end
910
    end
911

912
    def initialize(direction, migrations, target_version = nil)
913
      raise StandardError.new("This database does not yet support migrations") unless Base.connection.supports_migrations?
914

915 916 917
      @direction         = direction
      @target_version    = target_version
      @migrated_versions = nil
918
      @migrations        = migrations
919

920 921
      validate(@migrations)

922
      Base.connection.initialize_schema_migrations_table
923 924 925
    end

    def current_version
926
      migrated.max || 0
927
    end
928

929 930 931
    def current_migration
      migrations.detect { |m| m.version == current_version }
    end
932
    alias :current :current_migration
933

934
    def run
B
bondarev 已提交
935 936 937 938
      migration = migrations.detect { |m| m.version == @target_version }
      raise UnknownMigrationVersionError.new(@target_version) if migration.nil?
      unless (up? && migrated.include?(migration.version.to_i)) || (down? && !migrated.include?(migration.version.to_i))
        begin
N
Neeraj Singh 已提交
939
          execute_migration_in_transaction(migration, @direction)
B
bondarev 已提交
940
        rescue => e
941
          canceled_msg = use_transaction?(migration) ? ", this migration was canceled" : ""
B
bondarev 已提交
942 943
          raise StandardError, "An error has occurred#{canceled_msg}:\n\n#{e}", e.backtrace
        end
944
      end
945
    end
946

947
    def migrate
948
      if !target && @target_version && @target_version > 0
949 950
        raise UnknownMigrationVersionError.new(@target_version)
      end
951

952
      runnable.each do |migration|
953
        Base.logger.info "Migrating to #{migration.name} (#{migration.version})" if Base.logger
954

955
        begin
N
Neeraj Singh 已提交
956
          execute_migration_in_transaction(migration, @direction)
957
        rescue => e
958
          canceled_msg = use_transaction?(migration) ? "this and " : ""
959
          raise StandardError, "An error has occurred, #{canceled_msg}all later migrations canceled:\n\n#{e}", e.backtrace
960
        end
961
      end
962 963 964 965 966 967 968 969 970 971 972
    end

    def runnable
      runnable = migrations[start..finish]
      if up?
        runnable.reject { |m| ran?(m) }
      else
        # skip the last migration if we're headed down, but not ALL the way down
        runnable.pop if target
        runnable.find_all { |m| ran?(m) }
      end
973
    end
974

975
    def migrations
976
      down? ? @migrations.reverse : @migrations.sort_by(&:version)
977 978
    end

979
    def pending_migrations
980
      already_migrated = migrated
981
      migrations.reject { |m| already_migrated.include?(m.version) }
982 983 984
    end

    def migrated
985
      @migrated_versions ||= Set.new(self.class.get_all_versions)
986 987
    end

988
    private
989 990 991 992
    def ran?(migration)
      migrated.include?(migration.version.to_i)
    end

N
Neeraj Singh 已提交
993 994 995 996 997 998 999
    def execute_migration_in_transaction(migration, direction)
      ddl_transaction(migration) do
        migration.migrate(direction)
        record_version_state_after_migrating(migration.version)
      end
    end

1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    def target
      migrations.detect { |m| m.version == @target_version }
    end

    def finish
      migrations.index(target) || migrations.size - 1
    end

    def start
      up? ? 0 : (migrations.index(current) || 0)
    end

1012 1013 1014
    def validate(migrations)
      name ,= migrations.group_by(&:name).find { |_,v| v.length > 1 }
      raise DuplicateMigrationNameError.new(name) if name
1015

1016 1017 1018 1019
      version ,= migrations.group_by(&:version).find { |_,v| v.length > 1 }
      raise DuplicateMigrationVersionError.new(version) if version
    end

1020
    def record_version_state_after_migrating(version)
1021
      if down?
1022 1023
        migrated.delete(version)
        ActiveRecord::SchemaMigration.where(:version => version.to_s).delete_all
1024
      else
1025 1026
        migrated << version
        ActiveRecord::SchemaMigration.create!(:version => version.to_s)
1027
      end
1028
    end
1029

1030 1031 1032 1033 1034 1035 1036 1037 1038
    def up?
      @direction == :up
    end

    def down?
      @direction == :down
    end

    # Wrap the migration in a transaction only if supported by the adapter.
1039 1040
    def ddl_transaction(migration)
      if use_transaction?(migration)
1041
        Base.transaction { yield }
1042
      else
1043
        yield
1044
      end
1045
    end
1046 1047 1048 1049

    def use_transaction?(migration)
      !migration.disable_ddl_transaction && Base.connection.supports_ddl_transactions?
    end
1050
  end
1051
end