class Gitlab::QA::Component::PostgreSQL

def initialize

def initialize
  @docker = Docker::Engine.new
  @environment = {}
end

def instance

def instance
  prepare
  start
  wait_until_ready
  yield self
ensure
  teardown
end

def name

def name
  @name ||= "postgres"
end

def prepare

def prepare
  @docker.pull(POSTGRES_IMAGE, POSTGRES_IMAGE_TAG)
  return if @docker.network_exists?(network)
  @docker.network_create(network)
end

def run_psql(command)

def run_psql(command)
  @docker.exec(name, %(psql -U postgres #{command}))
end

def start

def start
  @docker.run(POSTGRES_IMAGE, POSTGRES_IMAGE_TAG) do |command|
    command << "-d"
    command << "--name #{name}"
    command << "--net #{network}"
    command.env("POSTGRES_PASSWORD", "SQL_PASSWORD")
  end
end

def teardown

def teardown
  @docker.stop(name)
  @docker.remove(name)
end

def wait_until_ready

def wait_until_ready
  start = Time.now
  begin
    run_psql 'template1'
  rescue StandardError
    retry if Time.now - start < 30
    raise
  end
end