]> git.openstreetmap.org Git - chef.git/blob - cookbooks/postgresql/libraries/postgresql.rb
Fix some rubocop detected style issues
[chef.git] / cookbooks / postgresql / libraries / postgresql.rb
1 require 'chef/mixin/command'
2
3 class Chef
4   class PostgreSQL
5     include Chef::Mixin::Command
6
7     TABLE_PRIVILEGES = [
8       :select, :insert, :update, :delete, :truncate, :references, :trigger
9     ]
10
11     def initialize(cluster)
12       @cluster = cluster
13     end
14
15     def execute(options)
16       # Create argument array
17       args = []
18
19       # Build the arguments
20       args.push("--command=\"#{options[:command].gsub('"', '\\"')}\"") if options[:command]
21       args.push("--file=#{options[:file]}") if options[:file]
22
23       # Get the database to use
24       database = options[:database] || "template1"
25
26       # Build the command to run
27       command = "/usr/bin/psql --cluster #{@cluster} #{args.join(' ')} #{database}"
28
29       # Get the user and group to run as
30       user = options[:user] || "postgres"
31       group = options[:group] || "postgres"
32
33       # Run the command
34       run_command(:command => command, :user => user, :group => group)
35     end
36
37     def query(sql, options = {})
38       # Get the database to use
39       database = options[:database] || "template1"
40
41       # Construct the command string
42       command = "/usr/bin/psql --cluster #{@cluster} --no-align --command='#{sql}' #{database}"
43
44       # Run the query
45       status, stdout, stderr = output_of_command(command, :user => "postgres", :group => "postgres")
46       handle_command_failures(status, "STDOUT: #{stdout}\nSTDERR: #{stderr}", :output_on_failure => true)
47
48       # Split the output into lines
49       lines = stdout.split("\n")
50
51       # Remove the "(N rows)" line from the end
52       lines.pop
53
54       # Get the field names
55       fields = lines.shift.split("|")
56
57       # Extract the record data
58       lines.collect do |line|
59         record = {}
60         fields.zip(line.split("|")) { |name, value| record[name.to_sym] = value }
61         record
62       end
63     end
64
65     def users
66       @users ||= query("SELECT * FROM pg_user").inject({}) do |users, user|
67         users[user[:usename]] = {
68           :superuser => user[:usesuper] == "t",
69           :createdb => user[:usercreatedb] == "t",
70           :createrole => user[:usecatupd] == "t",
71           :replication => user[:userepl] == "t"
72         }
73         users
74       end
75     end
76
77     def databases
78       @databases ||= query("SELECT d.datname, u.usename, d.encoding, d.datcollate, d.datctype FROM pg_database AS d INNER JOIN pg_user AS u ON d.datdba = u.usesysid").inject({}) do |databases, database|
79         databases[database[:datname]] = {
80           :owner => database[:usename],
81           :encoding => database[:encoding],
82           :collate => database[:datcollate],
83           :ctype => database[:datctype]
84         }
85         databases
86       end
87     end
88
89     def extensions(database)
90       @extensions ||= {}
91       @extensions[database] ||= query("SELECT extname, extversion FROM pg_extension", :database => database).inject({}) do |extensions, extension|
92         extensions[extension[:extname]] = {
93           :version => extension[:extversion]
94         }
95         databases
96       end
97     end
98
99     def tables(database)
100       @tables ||= {}
101       @tables[database] ||= query("SELECT n.nspname, c.relname, u.usename, c.relacl FROM pg_class AS c INNER JOIN pg_user AS u ON c.relowner = u.usesysid INNER JOIN pg_namespace AS n ON c.relnamespace = n.oid", :database => database).inject({}) do |tables, table|
102         name = "#{table[:nspname]}.#{table[:relname]}"
103
104         tables[name] = {
105           :owner => table[:usename],
106           :permissions => parse_acl(table[:relacl] || "{}")
107         }
108
109         tables
110       end
111     end
112
113   private
114
115     def parse_acl(acl)
116       acl.sub(/^\{(.*)\}$/, "\\1").split(",").inject({}) do |permissions, entry|
117         entry = entry.sub(/^"(.*)"$/) { $1.gsub(/\\"/, '"') }.sub(/\/.*$/, "")
118         user, privileges = entry.split("=")
119
120         user = user.sub(/^"(.*)"$/, "\\1")
121         user = "public" if user == ""
122
123         permissions[user] = {
124           "a" => :insert, "r" => :select, "w" => :update, "d" => :delete,
125           "D" => :truncate, "x" => :references, "t" => :trigger
126         }.values_at(*(privileges.chars)).compact
127
128         permissions
129       end
130     end
131   end
132 end