Last active
May 2, 2021 15:29
-
-
Save cpanderson/b1dee0d3800f80e2472b2a703eba2006 to your computer and use it in GitHub Desktop.
Rails Postgres Database Snapshots
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
namespace :db do | |
desc "Backup the database to a file and manage archives" | |
task :backup => [:environment] do | |
datestamp = Time.now.strftime("%Y-%m-%d_%H-%M-%S") | |
database = Rails.env.downcase | |
max_backups = 48 | |
base_path = "db" | |
backup_base = File.join(base_path, 'backups') | |
backup_file = "#{Rails.env}_#{datestamp}.db.gz" | |
backup_file_path = File.join(backup_base, backup_file) | |
# create | |
FileUtils.makedirs(backup_base) | |
sh "pg_dump #{database} | gzip -c > #{backup_file_path}" | |
system "cd #{backup_base} && ln -fs #{backup_file} latest_#{Rails.env}_db.gz" | |
puts "created backup: #{backup_file}" | |
# remove archives | |
all_backups = Dir.glob(File.join(backup_base, "#{Rails.env}*.gz")).sort.reverse | |
if all_backups.size > max_backups | |
unwanted_backups = all_backups[max_backups..-1] | |
unwanted_backups.each do |unwanted_backup| | |
FileUtils.rm(unwanted_backup) | |
puts "deleted #{unwanted_backup}" | |
end | |
puts "Deleted #{unwanted_backups.length} backups, #{all_backups.length - unwanted_backups.length} backups available" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment