Method: Gleis::Database.push

Defined in:
lib/gleis/database.rb

.push(app_name, local_name) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/gleis/database.rb', line 77

def self.push(app_name, local_name)
  token = Token.check
  Utils.check_for_local_pg_command('pg_dump')
  Utils.check_for_local_pg_command('pg_restore')
  url = Config.get_env_var(app_name, token, 'DATABASE_URL')
  abort('There is no database configured under the DATABASE_URL variable.') unless url
  ENV['PGCONNECT_TIMEOUT'] = '5'
  # Check if database is empty
  sql_statement = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public'"
  table_count = `psql #{url} -t -A -c "#{sql_statement}"`.chomp
  if table_count.to_i.zero?
    # Check connection to local database
    unless system("psql -c 'SELECT 1' #{local_name} >/dev/null 2>&1")
      abort("Failed to connect to local database #{local_name}, please check " \
        'that the database name is correct and that you have access to it.')
    end
    if system("pg_dump -Fc -x #{local_name} | pg_restore -O -n public -d #{url}")
      puts "Successfully pushed local database #{local_name} to database configured at DATABASE_URL."
    else
      puts "Failed to push local database #{local_name} to DATABASE_URL."
    end
  else
    puts 'The database configured at DATABASE_URL already contains data, please empty it first.'
  end
end