7962669c1a0502b96f60ca556e91c51c582ad634
[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 command()
4     if ((! resource[:unless]) or (resource[:unless].empty?))
5       if (resource[:refreshonly])
6         # So, if there's no 'unless', and we're in "refreshonly" mode,
7         # we need to return the target command here.  If we don't,
8         # then Puppet will generate an event indicating that this
9         # property has changed.
10         return resource[:command]
11       end
12
13       # if we're not in refreshonly mode, then we return nil,
14       # which will cause Puppet to sync this property.  This
15       # is what we want if there is no 'unless' value specified.
16       return nil
17     end
18
19     output, status = run_unless_sql_command(resource[:unless])
20
21     if status != 0
22       self.fail("Error evaluating 'unless' clause: '#{output}'")
23     end
24     result_count = output.strip.to_i
25     if result_count > 0
26       # If the 'unless' query returned rows, then we don't want to execute
27       # the 'command'.  Returning the target 'command' here will cause
28       # Puppet to treat this property as already being 'insync?', so it
29       # won't call the setter to run the 'command' later.
30       return resource[:command]
31     end
32
33     # Returning 'nil' here will cause Puppet to see this property
34     # as out-of-sync, so it will call the setter later.
35     nil
36   end
37
38   def command=(val)
39     output, status = run_sql_command(val)
40
41     if status != 0
42       self.fail("Error executing SQL; psql returned #{status}: '#{output}'")
43     end
44   end
45
46
47   def run_unless_sql_command(sql)
48     # for the 'unless' queries, we wrap the user's query in a 'SELECT COUNT',
49     # which makes it easier to parse and process the output.
50     run_sql_command('SELECT COUNT(*) FROM (' <<  sql << ') count')
51   end
52
53   def run_sql_command(sql)
54     command = [resource[:psql_path]]
55     command.push("-d", resource[:db]) if resource[:db]
56     command.push("-t", "-c", sql)
57
58     if resource[:cwd]
59       Dir.chdir resource[:cwd] do
60         Puppet::Util::SUIDManager.run_and_capture(command, resource[:psql_user], resource[:psql_group])
61       end
62     else
63       Puppet::Util::SUIDManager.run_and_capture(command, resource[:psql_user], resource[:psql_group])
64     end
65   end
66
67 end