ActiveRecord finding existing table indexes

后端 未结 4 867
逝去的感伤
逝去的感伤 2021-02-05 00:50

I am writing a migration generator for a plugin I am writing and I need to to be able to find what unique indexes a table has so I can modify existing unique indexes to become a

相关标签:
4条回答
  • 2021-02-05 01:33

    If you just want to see all the indexes for a particular table you can do:

    ActiveRecord::Base.connection.indexes('my_table_name').map(&:name)
    
    0 讨论(0)
  • 2021-02-05 01:39

    Just an update for cleaner inspection. As I had many tables I was finding it difficult to search for specific stuffs.

      ActiveRecord::Base.connection.tables.each do |table|
      indexes = ActiveRecord::Base.connection.indexes(table)
      if indexes.length > 0
        puts "====>  #{table} <===="
        indexes.each do |ind|
          puts "----> #{ind.name}"
        end
        puts "====>  #{table} <===="
        2.times{ puts ''}
      end
    end
    

    This will be of quick setup.

    0 讨论(0)
  • 2021-02-05 01:39

    Just in case you have multiple DBs and the proposed ActiveRecord::Base.connection.indexes(table).inspect doesn't work because it is pointing to other DBs. You can do this in your rails console.

    • Find the model you care, let's say "User"
    • User.connection.indexes("users").inspect
    • profit
    0 讨论(0)
  • 2021-02-05 01:44

    This works with MySQL, SQLite3, and Postgres:

    ActiveRecord::Base.connection.tables.each do |table|
        puts ActiveRecord::Base.connection.indexes(table).inspect
    end
    

    But I think it only gives you the indexes you specifically created.

    Also, to find out which adapter is in use:

    ActiveRecord::Base.connection.class
    
    0 讨论(0)
提交回复
热议问题