Home > Software engineering >  ActiveRecord how to check whether a table is partitioned?
ActiveRecord how to check whether a table is partitioned?

Time:07-13

I have a table that might be partitioned in certain environments but I would like to verify it in runtime rather than checking the environment name.

How can I do it in ActiveRecord?

The database is MySQL.

CodePudding user response:

I'd query the INFORMATION_SCHEMA.PARTITIONS table to see if the table has greater than 1 partition.

SELECT COUNT(*) FROM INFORMATION_SCHEMA.PARTITIONS
WHERE TABLE_SCHEMA=? AND TABLE_NAME=?

If the table is not partitioned, the count of matching rows is 1. If the table is partitioned, it will be greater than 1.

I'll leave it to you to adapt this to an ActiveRecord solution, but you should be able to query it as a direct query like you were doing with SHOW CREATE TABLE.


Added Ruby(ActiveRecord) version:

def table_is_partitioned?(table_name)
  sql = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?"
  ActiveRecord::Base.connection.select_value(sql, nil, [table_name, ActiveRecord::Base.connection.current_database]) > 1
end

CodePudding user response:

Perhaps someone knows a better way but for now, the method below seems to work:

def table_is_partitioned?(name)
  ActiveRecord::Base.connection.execute("SHOW CREATE TABLE #{name}").first.join('').include?('PARTITION BY')
end
  • Related