Skip to content

Instantly share code, notes, and snippets.

@rob-murray
Created November 8, 2016 09:55
Show Gist options
  • Save rob-murray/39e88448d60d93299ae36e00fbe54f2f to your computer and use it in GitHub Desktop.
Save rob-murray/39e88448d60d93299ae36e00fbe54f2f to your computer and use it in GitHub Desktop.
Helper to run a database command with given db config
# frozen_string_literal: true
# Helper to run a database command with given db config
class DbRunner
RESTORE_CMD_TEMPLATE = <<-CMD.squish
pg_restore -1 --disable-triggers -a -h %{host} -U %{username} -w -d %{database} #{Rails.root}/tmp/full-dump.pgsql
CMD
BACKUP_CMD_TEMPLATE = <<-CMD.squish
pg_dump --clean -w -U %{username} -d %{database} -h %{host} --format=c --compress=9 -T ar_internal_metadata -T schema_migrations -O > #{Rails.root}/tmp/full-dump.pgsql
CMD
def self.restore!
new.run_template(RESTORE_CMD_TEMPLATE)
end
def self.backup!
new.run_template(BACKUP_CMD_TEMPLATE)
end
def initialize(db_config = ActiveRecord::Base.connection_config)
@db_config = db_config
end
def run_template(cmd_template)
execute cmd_template % @db_config
end
private
def execute(command)
system(command)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment