Sha256: fe60c133a761e8eeaa5ab78bdbad42b2951f92909eacb2ec465453ad4d831b12

Contents?: true

Size: 1.43 KB

Versions: 1

Compression:

Stored size: 1.43 KB

Contents

require "English"

class AwesomeBackup::PostgresBackupService < AwesomeBackup::ApplicationService
  def execute
    result = `#{pg_dump_command} > \"#{tempfile_path}\"`
    raise "Command failed: #{result}" unless $CHILD_STATUS.exitstatus.zero?

    backup = AwesomeBackup::PostgresBackup.create!
    backup.file.attach(
      io: File.open(tempfile_path),
      filename: "database.dump"
    )

    succeed!(backup: backup)
  end

private

  def database_config
    @database_config ||= Rails.configuration.database_configuration.fetch(Rails.env)
  end

  def pg_dump_command
    command = "pg_dump --format=c"
    command << pg_dump_username_argument.to_s
    command << pg_dump_host_argument.to_s
    command << pg_dump_port_argument.to_s

    if database_config["password"].present?
      command.prepend("PGPASSWORD=\"#{database_config.fetch("password")}\" ")
    else
      command << " --no-password"
    end

    command << " \"#{database_config.fetch("database")}\""
    command
  end

  def pg_dump_host_argument
    " \"--host=#{database_config.fetch("host")}\"" if database_config["host"].present?
  end

  def pg_dump_port_argument
    " \"--port=#{database_config.fetch("port")}\"" if database_config["port"].present?
  end

  def pg_dump_username_argument
    " -U \"#{database_config.fetch("username")}\"" if database_config["username"].present?
  end

  def tempfile_path
    @tempfile_path ||= "#{Dir.tmpdir}/#{SecureRandom.hex}.dump"
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
awesome_backup-0.0.0 app/services/awesome_backup/postgres_backup_service.rb