newer pg module
[mirror/dsa-puppet.git] / 3rdparty / modules / postgresql / lib / puppet / provider / postgresql_psql / ruby.rb
1 Puppet::Type.type(:postgresql_psql).provide(:ruby) do
2
3   def run_unless_sql_command(sql)
4     # for the 'unless' queries, we wrap the user's query in a 'SELECT COUNT',
5     # which makes it easier to parse and process the output.
6     run_sql_command('SELECT COUNT(*) FROM (' <<  sql << ') count')
7   end
8
9   def run_sql_command(sql)
10     if resource[:search_path]
11       sql = "set search_path to #{Array(resource[:search_path]).join(',')}; #{sql}"
12     end
13
14     command = [resource[:psql_path]]
15     command.push("-d", resource[:db]) if resource[:db]
16     command.push("-p", resource[:port]) if resource[:port]
17     command.push("-t", "-c", '"' + sql.gsub('"', '\"') + '"')
18
19     environment = get_environment
20
21     if resource[:cwd]
22       Dir.chdir resource[:cwd] do
23         run_command(command, resource[:psql_user], resource[:psql_group], environment)
24       end
25     else
26       run_command(command, resource[:psql_user], resource[:psql_group], environment)
27     end
28   end
29
30   private
31
32   def get_environment
33     environment = (resource[:connect_settings] || {}).dup
34     if envlist = resource[:environment]
35       envlist = [envlist] unless envlist.is_a? Array
36       envlist.each do |setting|
37         if setting =~ /^(\w+)=((.|\n)+)$/
38           env_name = $1
39           value = $2
40           if environment.include?(env_name) || environment.include?(env_name.to_sym)
41             if env_name == 'NEWPGPASSWD'
42               warning "Overriding environment setting '#{env_name}' with '****'"
43             else
44               warning "Overriding environment setting '#{env_name}' with '#{value}'"
45             end
46           end
47           environment[env_name] = value
48         else
49           warning "Cannot understand environment setting #{setting.inspect}"
50         end
51       end
52     end
53     return environment
54   end
55
56   def run_command(command, user, group, environment)
57     command = command.join ' '
58     if Puppet::PUPPETVERSION.to_f < 3.0
59       require 'puppet/util/execution'
60       Puppet::Util::Execution.withenv environment do
61         Puppet::Util::SUIDManager.run_and_capture(command, user, group)
62       end
63     elsif Puppet::PUPPETVERSION.to_f < 3.4
64       Puppet::Util.withenv environment do
65         Puppet::Util::SUIDManager.run_and_capture(command, user, group)
66       end
67     else
68       output = Puppet::Util::Execution.execute(command, {
69         :uid                => user,
70         :gid                => group,
71         :failonfail         => false,
72         :combine            => true,
73         :override_locale    => true,
74         :custom_environment => environment,
75       })
76       [output, $CHILD_STATUS.dup]
77     end
78   end
79
80 end