Method: Inspec::Resources::OracledbSession#query

Defined in:
lib/resources/oracledb_session.rb

#query(q) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/resources/oracledb_session.rb', line 51

def query(q)
  escaped_query = q.gsub(/\\/, '\\\\').gsub(/"/, '\\"')
  # escape tables with $
  escaped_query = escaped_query.gsub('$', '\\$')

  p = nil
  # use sqlplus if sqlcl is not available
  if @sqlcl_bin and inspec.command(@sqlcl_bin).exist?
    bin = @sqlcl_bin
    opts = "set sqlformat csv\nSET FEEDBACK OFF"
    p = :parse_csv_result
  else
    bin = @sqlplus_bin
    opts = "SET MARKUP HTML ON\nSET PAGESIZE 32000\nSET FEEDBACK OFF"
    p = :parse_html_result
  end

  query = verify_query(escaped_query)
  query += ';' unless query.end_with?(';')
  if @db_role.nil?
    command = %{#{bin} "#{@user}"/"#{@password}"@#{@host}:#{@port}/#{@service} <<EOC\n#{opts}\n#{query}\nEXIT\nEOC}
  elsif @su_user.nil?
    command = %{#{bin} "#{@user}"/"#{@password}"@#{@host}:#{@port}/#{@service} as #{@db_role} <<EOC\n#{opts}\n#{query}\nEXIT\nEOC}
  else
    command = %{su - #{@su_user} -c "env ORACLE_SID=#{@service} #{bin} / as #{@db_role} <<EOC\n#{opts}\n#{query}\nEXIT\nEOC"}
  end
  cmd = inspec.command(command)

  out = cmd.stdout + "\n" + cmd.stderr
  if out.downcase =~ /^error/
    # TODO: we need to throw an exception here
    # change once https://github.com/chef/inspec/issues/1205 is in
    warn "Could not execute the sql query #{out}"
    DatabaseHelper::SQLQueryResult.new(cmd, Hashie::Mash.new({}))
  end
  DatabaseHelper::SQLQueryResult.new(cmd, send(p, cmd.stdout))
end