Skip to content

Instantly share code, notes, and snippets.

@leemour
Created May 4, 2018 19:43
Show Gist options
  • Save leemour/4f0779929315b08a15c48a8a8915b9bf to your computer and use it in GitHub Desktop.
Save leemour/4f0779929315b08a15c48a8a8915b9bf to your computer and use it in GitHub Desktop.
Backup all db records older than x
namespace :db do
desc "Backup DB as separate schema"
task :backup_to_schema, [:created_at] => :environment do |t, args|
schema = 'copy'
created_at = args.created_at || 2.years.ago
ApplicationRecord.connection.execute(
"DROP SCHEMA #{schema} CASCADE;
CREATE SCHEMA copy"
)
ActiveRecord::Base.connection.execute "SET search_path TO public, #{schema}"
File.read(File.expand_path '~/tables.txt').each_line do |table_name|
table_name.sub! /\n/, ''
unless ApplicationRecord.connection.table_exists? table_name
raise "#{table_name} doesn't exist in DB"
end
ApplicationRecord.connection.execute(
"create table #{schema}.#{table_name} (like #{table_name} including all)")
puts "Created #{table_name}"
if ApplicationRecord.connection.column_exists? table_name, 'created_at'
ApplicationRecord.connection.execute(
"INSERT INTO #{schema}.#{table_name} SELECT * FROM #{table_name}
WHERE created_at < '#{created_at.to_formatted_s :db}'")
else
ApplicationRecord.connection.execute(
"INSERT INTO #{schema}.#{table_name} SELECT * FROM #{table_name}")
end
puts "Copied #{table_name}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment