public
Description: Ruby on Rails
Homepage: http://rubyonrails.org
Clone URL: git://github.com/rails/rails.git
Cache migrated versions list in Migrator and use it to fetch the latest migrated 
version name [#845 state:resolved]

Also optimized Migrator#current_version class method to fetch
only the latest version number and not all of them.

With this change no matter how many migrations there are the
schema_migrations table is only SELECTed from once.

Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
Tarmo Tänav (author)
Mon Aug 25 18:55:57 -0700 2008
jeremy (committer)
Mon Aug 25 22:03:47 -0700 2008
commit  3d2ac918b987ef0cff34f6a7fdd20926b7a9e5d9
tree    c59dd78994dd9892c0707947d4e02d6c79b2556d
parent  4bcd64c9e93af2f13dc7309cd76bb764e4d7d23d
...
407
408
409
410
411
412
413
 
 
 
414
415
416
...
426
427
428
429
 
430
431
432
...
518
519
520
521
 
522
523
524
525
526
527
 
528
 
529
530
 
531
532
533
...
407
408
409
 
 
 
 
410
411
412
413
414
415
...
425
426
427
 
428
429
430
431
...
517
518
519
 
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
0
@@ -407,10 +407,9 @@ module ActiveRecord
0
       end
0
 
0
       def current_version
0
-        version = Base.connection.select_values(
0
-          "SELECT version FROM #{schema_migrations_table_name}"
0
-        ).map(&:to_i).max rescue nil
0
-        version || 0
0
+        Base.connection.select_value(
0
+          "SELECT MAX(CAST(version AS integer)) FROM #{schema_migrations_table_name}"
0
+        ).to_i rescue 0
0
       end
0
 
0
       def proper_table_name(name)
0
@@ -426,7 +425,7 @@ module ActiveRecord
0
     end
0
 
0
     def current_version
0
-      self.class.current_version
0
+      migrated.last || 0
0
     end
0
     
0
     def current_migration
0
@@ -518,16 +517,19 @@ module ActiveRecord
0
 
0
     def migrated
0
       sm_table = self.class.schema_migrations_table_name
0
-      Base.connection.select_values("SELECT version FROM #{sm_table}").map(&:to_i).sort
0
+      @migrated_versions ||= Base.connection.select_values("SELECT version FROM #{sm_table}").map(&:to_i).sort
0
     end
0
 
0
     private
0
       def record_version_state_after_migrating(version)
0
         sm_table = self.class.schema_migrations_table_name
0
 
0
+        @migrated_versions ||= []
0
         if down?
0
+          @migrated_versions.delete(version.to_i)
0
           Base.connection.update("DELETE FROM #{sm_table} WHERE version = '#{version}'")
0
         else
0
+          @migrated_versions.push(version.to_i).sort!
0
           Base.connection.insert("INSERT INTO #{sm_table} (version) VALUES ('#{version}')")
0
         end
0
       end

Comments