-
-
Save ChrisLusted/f8f55bc8c0596fdaac90 to your computer and use it in GitHub Desktop.
Rake tasks to maintain Postgres tables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ?