]> git.openstreetmap.org Git - chef.git/blob - cookbooks/postgresql/libraries/postgresql.rb
Force database drops on postgres versions which support it
[chef.git] / cookbooks / postgresql / libraries / postgresql.rb
1 require "chef/mixin/shell_out"
2
3 module OpenStreetMap
4   class PostgreSQL
5     include Chef::Mixin::ShellOut
6
7     TABLE_PRIVILEGES = [
8       :select, :insert, :update, :delete, :truncate, :references, :trigger
9     ].freeze
10
11     def initialize(cluster)
12       @cluster = cluster
13     end
14
15     def version
16       @cluster.split("/").first.to_f
17     end
18
19     def execute(options)
20       # Create argument array
21       args = []
22
23       # Add the cluster
24       args.push("--cluster")
25       args.push(@cluster)
26
27       # Set output format
28       args.push("--no-align") unless options.fetch(:align, true)
29
30       # Add any SQL command to execute
31       if options[:command]
32         args.push("--command")
33         args.push(options[:command])
34       end
35
36       # Add any file to execute SQL commands from
37       if options[:file]
38         args.push("--file")
39         args.push(options[:file])
40       end
41
42       # Add the database name
43       args.push(options[:database] || "template1")
44
45       # Get the user and group to run as
46       user = options[:user] || "postgres"
47       group = options[:group] || "postgres"
48
49       # Run the command
50       shell_out!("/usr/bin/psql", *args, :user => user, :group => group)
51     end
52
53     def query(sql, options = {})
54       # Run the query
55       result = execute(options.merge(:command => sql, :align => false))
56
57       # Split the output into lines
58       lines = result.stdout.split("\n")
59
60       # Remove the "(N rows)" line from the end
61       lines.pop
62
63       # Get the field names
64       fields = lines.shift.split("|")
65
66       # Extract the record data
67       lines.collect do |line|
68         record = {}
69         fields.zip(line.split("|")) { |name, value| record[name.to_sym] = value }
70         record
71       end
72     end
73
74     def users
75       @users ||= query("SELECT * FROM pg_user").each_with_object({}) do |user, users|
76         users[user[:usename]] = {
77           :superuser => user[:usesuper] == "t",
78           :createdb => user[:usercreatedb] == "t",
79           :createrole => user[:usecatupd] == "t",
80           :replication => user[:userepl] == "t"
81         }
82       end
83     end
84
85     def databases
86       @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").each_with_object({}) do |database, databases|
87         databases[database[:datname]] = {
88           :owner => database[:usename],
89           :encoding => database[:encoding],
90           :collate => database[:datcollate],
91           :ctype => database[:datctype]
92         }
93       end
94     end
95
96     def extensions(database)
97       @extensions ||= {}
98       @extensions[database] ||= query("SELECT extname, extversion FROM pg_extension", :database => database).each_with_object({}) do |extension, extensions|
99         extensions[extension[:extname]] = {
100           :version => extension[:extversion]
101         }
102       end
103     end
104
105     def tablespaces
106       @tablespaces ||= query("SELECT spcname, usename FROM pg_tablespace AS t INNER JOIN pg_user AS u ON t.spcowner = u.usesysid").each_with_object({}) do |tablespace, tablespaces|
107         tablespaces[tablespace[:spcname]] = {
108           :owner => tablespace[:usename]
109         }
110       end
111     end
112
113     def tables(database)
114       @tables ||= {}
115       @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).each_with_object({}) do |table, tables|
116         name = "#{table[:nspname]}.#{table[:relname]}"
117
118         tables[name] = {
119           :owner => table[:usename],
120           :permissions => parse_acl(table[:relacl] || "{}")
121         }
122       end
123     end
124
125     private
126
127     def parse_acl(acl)
128       acl.sub(/^\{(.*)\}$/, "\\1").split(",").each_with_object({}) do |entry, permissions|
129         entry = entry.sub(/^"(.*)"$/) { Regexp.last_match[1].gsub(/\\"/, '"') }.sub(%r{/.*$}, "")
130         user, privileges = entry.split("=")
131
132         user = user.sub(/^"(.*)"$/, "\\1")
133         user = "public" if user == ""
134
135         permissions[user] = {
136           "a" => :insert, "r" => :select, "w" => :update, "d" => :delete,
137           "D" => :truncate, "x" => :references, "t" => :trigger
138         }.values_at(*privileges.chars).compact
139       end
140     end
141   end
142 end