Class: Inspec::Resources::PostgresSession

Inherits:
Object
  • Object
show all
Defined in:
lib/resources/postgres_session.rb

Instance Method Summary collapse

Constructor Details

#initialize(user, pass, host = nil) ⇒ PostgresSession

Returns a new instance of PostgresSession.



43
44
45
46
47
# File 'lib/resources/postgres_session.rb', line 43

def initialize(user, pass, host = nil)
  @user = user || 'postgres'
  @pass = pass
  @host = host || 'localhost'
end

Instance Method Details

#query(query, db = []) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/resources/postgres_session.rb', line 49

def query(query, db = [])
  dbs = db.map { |x| "-d #{x}" }.join(' ')
  # TODO: simple escape, must be handled by a library
  # that does this securely
  escaped_query = query.gsub(/\\/, '\\\\').gsub(/"/, '\\"').gsub(/\$/, '\\$')
  # run the query
  cmd = inspec.command("PGPASSWORD='#{@pass}' psql -U #{@user} #{dbs} -h #{@host} -A -t -c \"#{escaped_query}\"")
  out = cmd.stdout + "\n" + cmd.stderr
  if cmd.exit_status != 0 or
     out =~ /could not connect to .*/ or
     out.downcase =~ /^error/
    # skip this test if the server can't run the query
    skip_resource "Can't read run query #{query.inspect} on postgres_session: #{out}"
  else
    Lines.new(cmd.stdout.strip, "PostgreSQL query: #{query}")
  end
end