Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord finding existing table indexes

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 composite unique index. I have been trying to find a way to access what indexes a table has with ActiveRecord. I have only been able to find ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::indexes method, but unfortunately this is only available for the PosgreSQLAdapter. I need to be able to support the other major databases.

I first grepping the schema.rb file to find the indexes, this worked at first, but I soon realized this was a bad strategy.

I was thinking that if ActiveRecord does not provide a means to be able to do this for multiple database adapters, I may be able to write adapter specific queries to retrieve the index information from a table. If I need to resort to this method what would be a good way to determine the adapter in use?

If someone knows of a way to get ActiveRecord to list table index information that would be ideal.

like image 841
Sean McCleary Avatar asked Nov 05 '09 22:11

Sean McCleary


2 Answers

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 
like image 80
agregoire Avatar answered Sep 22 '22 07:09

agregoire


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.

like image 33
Abibullah Rahamathulah Avatar answered Sep 23 '22 07:09

Abibullah Rahamathulah