Skip to content

Instantly share code, notes, and snippets.

@kplawver
Created October 7, 2009 13:06
Show Gist options
  • Save kplawver/204015 to your computer and use it in GitHub Desktop.
Save kplawver/204015 to your computer and use it in GitHub Desktop.
I was tired of running optimize table by hand, so I wrote something do to it for me.
# Will run optimize table on either just that class's MySQL InnDB table, or on ALL of that connection's tables.
# Works only with MySQL InnoDB tables, but could be used to run repair if you're using MyISAM.
class ActiveRecord::Base
def self.optimize_table
begin
self.connection.execute("optimize table #{self.table_name}")
rescue Exception => e
logger.error("#{self.class_name} - error optimizing #{self.table_name}: #{e}")
else
logger.debug("#{self.class_name} - optimized table #{self.table_name}")
end
end
def self.optimize_all_tables
begin
self.connection.tables.each do |table|
self.connection.execute("optimize table #{table}")
end
rescue Exception => e
logger.error("ActiveRecord::Base.optimize_all_tables - error optimizing: #{e}")
else
logger.debug("ActiveRecord::Base.optimize_all_tables - all tables optimized")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment