| 1 |
# frozen_string_literal: true |
| 2 |
|
| 3 |
Puppet::Type.type(:postgresql_psql).provide(:ruby) do |
| 4 |
desc 'Postgres psql provider' |
| 5 |
def run_unless_sql_command(sql) |
| 6 |
# for the 'unless' queries, we wrap the user's query in a 'SELECT COUNT', |
| 7 |
# which makes it easier to parse and process the output. |
| 8 |
run_sql_command("SELECT COUNT(*) FROM (#{sql}) count") |
| 9 |
end |
| 10 |
|
| 11 |
def run_sql_command(sql) |
| 12 |
sql = "set search_path to #{Array(resource[:search_path]).join(',')}; #{sql}" if resource[:search_path] |
| 13 |
|
| 14 |
command = [resource[:psql_path]] |
| 15 |
command.push('-d', resource[:db]) if resource[:db] |
| 16 |
command.push('-p', resource[:port].to_s) if resource[:port] |
| 17 |
command.push('-t', '-X', '-c', sql) |
| 18 |
|
| 19 |
environment = fetch_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 fetch_environment |
| 33 |
environment = (resource[:connect_settings] || {}).dup |
| 34 |
envlist = resource[:environment] |
| 35 |
return environment unless envlist |
| 36 |
|
| 37 |
envlist = [envlist] unless envlist.is_a? Array |
| 38 |
envlist.each do |setting| |
| 39 |
if setting =~ %r{^(\w+)=((.|\n)+)$} |
| 40 |
env_name = Regexp.last_match(1) |
| 41 |
value = Regexp.last_match(2) |
| 42 |
if environment.include?(env_name) || environment.include?(env_name.to_sym) |
| 43 |
if env_name == 'NEWPGPASSWD' |
| 44 |
warning "Overriding environment setting '#{env_name}' with '****'" |
| 45 |
else |
| 46 |
warning "Overriding environment setting '#{env_name}' with '#{value}'" |
| 47 |
end |
| 48 |
end |
| 49 |
environment[env_name] = value |
| 50 |
else |
| 51 |
warning "Cannot understand environment setting #{setting.inspect}" |
| 52 |
end |
| 53 |
end |
| 54 |
environment |
| 55 |
end |
| 56 |
|
| 57 |
def run_command(command, user, group, environment) |
| 58 |
output = Puppet::Util::Execution.execute(command, uid: user, |
| 59 |
gid: group, |
| 60 |
failonfail: false, |
| 61 |
combine: true, |
| 62 |
override_locale: true, |
| 63 |
custom_environment: environment, |
| 64 |
sensitive: resource[:sensitive] == :true) |
| 65 |
[output, $CHILD_STATUS.dup] |
| 66 |
end |
| 67 |
end |