Skip to content
This repository
Browse code

Handle nil in add_index :length option in MySQL

Our schema.rb is being generated with an `add_index` line similar to this:

    add_index "foo", ["foo", "bar"], :name => "xxx", :length => {"foo"=>8, "bar=>nil}

This is the same as it was on Rails 3.1.3, however, now when that
schema.rb is evaluated, its generating bad SQL in MySQL:

    Mysql::Error: You have an error in your SQL syntax; check the manual
    that corresponds to your MySQL server version for the right syntax
    to use near '))' at line 1: CREATE UNIQUE INDEX
    `xxx` ON `foo` (`foo`(8), `bar`())

This commit adds a check for nil on the length attribute to prevent the
empty parens from being output.
  • Loading branch information...
commit 6cde635f34dc65a8c6f2d87ca995120fcf0ea25f 1 parent b1f8ba1
Paul Sadauskas authored January 24, 2012
2  activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
@@ -541,7 +541,7 @@ def add_index_length(option_strings, column_names, options = {})
541 541
         if options.is_a?(Hash) && length = options[:length]
542 542
           case length
543 543
           when Hash
544  
-            column_names.each {|name| option_strings[name] += "(#{length[name]})" if length.has_key?(name)}
  544
+            column_names.each {|name| option_strings[name] += "(#{length[name]})" if length.has_key?(name) && length[name].present?}
545 545
           when Fixnum
546 546
             column_names.each {|name| option_strings[name] += "(#{length})"}
547 547
           end
8  activerecord/test/cases/migration/index_test.rb
@@ -55,7 +55,7 @@ def test_remove_nonexistent_index
55 55
         assert_raise(ArgumentError) { connection.remove_index(table_name, "no_such_index") }
56 56
       end
57 57
 
58  
-      def test_add_index_length_limit
  58
+      def test_add_index_name_length_limit
59 59
         good_index_name = 'x' * connection.index_name_length
60 60
         too_long_index_name = good_index_name + 'x'
61 61
 
@@ -103,6 +103,12 @@ def test_named_index_exists
103 103
         assert connection.index_exists?(:testings, :foo, :name => "custom_index_name")
104 104
       end
105 105
 
  106
+      def test_add_index_attribute_length_limit
  107
+        connection.add_index :testings, [:foo, :bar], :length => {:foo => 10, :bar => nil}
  108
+
  109
+        assert connection.index_exists?(:testings, [:foo, :bar])
  110
+      end
  111
+
106 112
       def test_add_index
107 113
         connection.add_index("testings", "last_name")
108 114
         connection.remove_index("testings", "last_name")

0 notes on commit 6cde635

Please sign in to comment.
Something went wrong with that request. Please try again.