/
psql_backend.rb
71 lines (57 loc) · 2.14 KB
/
psql_backend.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
require 'pg'
require 'json'
class Hiera
module Backend
class Psql_backend
def initialize
Hiera.debug("Hiera PostgreSQL backend starting")
end
def lookup(key, scope, order_override, resolution_type)
answer = nil
Hiera.debug("Looking up #{key} in PostgreSQL backend")
Backend.datasources(scope, order_override) do |source|
connection.exec "SELECT value FROM config WHERE path=$1 AND key=$2", [source, key] do |result|
# Extra logging that we found the key. This can be outputted
# multiple times if the resolution type is array or hash but that
# should be expected as the logging will then tell the user ALL the
# places where the key is found.
Hiera.debug("Found #{key} in #{source}")
entry = result.first
return nil unless result.first
new_answer = JSON.load(entry.values_at('value'))
# for array resolution we just append to the array whatever
# we find, we then goes onto the next file and keep adding to
# the array
#
# for priority searches we break after the first found data item
case resolution_type
when :array
raise Exception, "Hiera type mismatch: expected Array and got #{new_answer.class}" unless new_answer.kind_of? Array or new_answer.kind_of? String
answer ||= []
answer << new_answer
when :hash
raise Exception, "Hiera type mismatch: expected Hash and got #{new_answer.class}" unless new_answer.kind_of? Hash
answer ||= {}
answer = Backend.merge_answer(new_answer,answer)
else
answer = new_answer
break
end
end
end
return answer
end
private
# Get a config key for this backend
def self.config(key)
Config[:psql][key.to_sym]
end
def self.connection
@connection ||= PGconn.open(config :connection)
end
def connection
self.class.connection
end
end
end
end