Skip to content

Instantly share code, notes, and snippets.

@ChrisLusted
Forked from romansklenar/db.rake
Last active September 19, 2016 07:51
Show Gist options
  • Save ChrisLusted/f8f55bc8c0596fdaac90 to your computer and use it in GitHub Desktop.
Save ChrisLusted/f8f55bc8c0596fdaac90 to your computer and use it in GitHub Desktop.
Rake tasks to maintain Postgres tables
# lib/tasks/db.rake
namespace :db do
desc 'Maintains database by running command as ANALYZE, VACUUM and REINDEX'
task maintain: :environment do
verbose = ENV['VERBOSE'].present?
connection = ActiveRecord::Base.connection
puts "Maintaining database #{connection.current_database} ..."
connection.execute("VACUUM FULL #{'VERBOSE' if verbose}")
connection.execute("ANALYZE #{'VERBOSE' if verbose}")
connection.execute("REINDEX DATABASE #{connection.current_database}")
puts "DONE."
end
desc 'Reindex all the tables'
task reindex_all: :environment do
verbose = ENV['VERBOSE'].present?
connection = ActiveRecord::Base.connection
connection.tables.each do |table|
next if table.match(/\Aschema_migrations\Z/)
puts "REINDEX database table #{table} ..."
connection.reset_pk_sequence!("#{table}")
puts "#{table} DONE."
end
end
desc 'Reindex a certain table. Will prompt for table name'
task reindex_table: :environment do
verbose = ENV['VERBOSE'].present?
connection = ActiveRecord::Base.connection
STDOUT.puts "What table would you like to reindex?"
table_name = STDIN.gets.strip
if connection.table_exists? table_name
puts "REINDEX database table #{table_name}..."
connection.reset_pk_sequence!("#{table_name}")
puts "#{table_name} REINDEX DONE."
else
puts "Sorry but the #{table_name} table does not exist."
end
end
end
@emad-elsaid
Copy link

How often do you execute the first 2 rake tasks? I thought of every day, but does it take too long to Vacuum/Analyze/Reindex ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment