When converting legacy frameworks over to Rails, I often desire to get things working with Migrations. More often than not, Rake craps out on me, when the tablenames are reserved keywords. I usually just change tablenames, to avoid the hassle, but, in keeping with my New Years Resolution of “If I have an annoying problem, fix it, don’t walk away”, here’s a quick homebrew solution for “rake db_schema_dump” that’ll ensure that you can mash your legacy db with its weird-ass tablenames into something useable..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
module ActiveRecord
  module ConnectionAdapters
    class MysqlAdapter < AbstractAdapter
      def indexes(table_name, name = nil)#:nodoc:
        indexes = []
        current_index = nil
        execute("SHOW KEYS FROM #{quote_column_name table_name}", name).each do |row|
          if current_index != row[2]
            next if row[2] == "PRIMARY" # skip the primary key
            current_index = row[2]
            indexes << IndexDefinition.new(row[0], row[2], row[1] == "0", [])
          end

          indexes.last.columns << row[4]
        end
        indexes
      end

      def columns(table_name, name = nil)#:nodoc:
        sql = "SHOW FIELDS FROM #{quote_column_name table_name}"
        columns = []
        execute(sql, name).each { |field| columns << MysqlColumn.new(field[0], field[4], field[1], field[2] == "YES") }
        columns
      end
    end
  end
end

I wish I knew of a leaner way to do this, but, short of having some kind of observer, or some cool trick that takes advantage of Ruby polymorphism, to which I am not privy, this will have to do. Maybe the ActiveRecord guys will escape tablenames in the next release, there are plenty of other people with the same issue!

Leave a Reply

 

Michael Cerna Chicago-based Rails Developer and Avid Musician. More ...

Search

Categories

  • Home (15)
  • Rails Plugins (5)
  • Pages (9)
  • Archives

    Tags

    BlogRoll