forked from theforeman/foreman_maintain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base_database.rb
174 lines (149 loc) · 5.57 KB
/
base_database.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
module ForemanMaintain
module Concerns
module BaseDatabase
def data_dir
if check_min_version('foreman', '2.0')
'/var/opt/rh/rh-postgresql12/lib/pgsql/data/'
else
'/var/lib/pgsql/data/'
end
end
def configuration
raise NotImplementedError
end
def config_files
[
'/etc/systemd/system/postgresql.service'
]
end
def local?(config = configuration)
['localhost', '127.0.0.1', `hostname`.strip].include? config['host']
end
def query(sql, config = configuration)
parse_csv(query_csv(sql, config))
end
def query_csv(sql, config = configuration)
psql(%{COPY (#{sql}) TO STDOUT WITH CSV HEADER}, config)
end
def psql(query, config = configuration)
if ping(config)
execute(psql_command(config),
:stdin => query,
:hidden_patterns => [config['password']])
else
raise_service_error
end
end
def ping(config = configuration)
execute?(psql_command(config),
:stdin => 'SELECT 1 as ping',
:hidden_patterns => [config['password']])
end
def backup_file_path(config = configuration)
dump_file_name = "#{config['database']}_#{Time.now.strftime('%Y-%m-%d_%H-%M-%S')}.dump"
"#{backup_dir}/#{dump_file_name}.bz2"
end
def dump_db(file, config = configuration)
execute!(dump_command(config) + " > #{file}", :hidden_patterns => [config['password']])
end
def restore_dump(file, localdb, config = configuration)
if localdb
dump_cmd = "runuser - postgres -c 'pg_restore -C -d postgres #{file}'"
execute!(dump_cmd)
else
# TODO: figure out how to completely ignore errors. Currently this
# sometimes exits with 1 even though errors are ignored by pg_restore
dump_cmd = base_command(config, 'pg_restore') +
' --no-privileges --clean --disable-triggers -n public ' \
"-d #{config['database']} #{file}"
execute!(dump_cmd, :hidden_patterns => [config['password']],
:valid_exit_statuses => [0, 1])
end
end
def restore_pg_globals(pg_globals, config = configuration)
execute!(base_command(config, 'psql') + " -f #{pg_globals} postgres 2>/dev/null",
:hidden_patterns => [config['password']])
end
def backup_local(backup_file, extra_tar_options = {})
dir = extra_tar_options.fetch(:data_dir, data_dir)
FileUtils.cd(dir) do
tar_options = {
:archive => backup_file,
:command => 'create',
:transform => 's,^,var/lib/pgsql/data/,S',
:files => '*'
}.merge(extra_tar_options)
feature(:tar).run(tar_options)
end
end
# TODO: refactor to use dump_db
def backup_db_command(file_path, config = configuration)
pg_dump_cmd = "pg_dump -Fc #{config['database']}"
"runuser - postgres -c '#{pg_dump_cmd}' | bzip2 -9 > #{file_path}"
end
# TODO: remove the backup file path tools from here. Lib Utils::Backup?
def backup_dir
@backup_dir ||= File.expand_path(ForemanMaintain.config.db_backup_dir)
end
def backup_global_objects(file)
execute!("runuser - postgres -c 'pg_dumpall -g > #{file}'")
end
def perform_backup(config = configuration)
file_path = backup_file_path(config)
backup_cmd = backup_db_command(file_path, config)
execute!(backup_cmd, :hidden_patterns => [config['password']])
puts "\n Note: Database backup file path - #{file_path}"
puts "\n In case of any exception, use above dump file to restore DB."
end
def table_exist?(table_name)
sql = <<-SQL
SELECT EXISTS ( SELECT *
FROM information_schema.tables WHERE table_name = '#{table_name}' )
SQL
result = query(sql)
return false if result.nil? || (result && result.empty?)
result.first['exists'].eql?('t')
end
def delete_records_by_ids(tbl_name, rec_ids)
quotize_rec_ids = rec_ids.map { |el| "'#{el}'" }.join(',')
unless quotize_rec_ids.empty?
psql(<<-SQL)
BEGIN;
DELETE FROM #{tbl_name} WHERE id IN (#{quotize_rec_ids});
COMMIT;
SQL
end
end
def find_base_directory(directory)
find_dir_containing_file(directory, 'postgresql.conf')
end
def dropdb(config = configuration)
if local?
execute!("runuser - postgres -c 'dropdb #{config['database']}'")
else
delete_statement = psql(<<-SQL)
select string_agg('drop table if exists \"' || tablename || '\" cascade;', '')
from pg_tables
where schemaname = 'public';
SQL
psql(delete_statement)
end
end
private
def base_command(config, command = 'psql')
"PGPASSWORD='#{config[%(password)]}' "\
"#{command} -h #{config['host'] || 'localhost'} "\
" -p #{config['port'] || '5432'} -U #{config['username']}"
end
def psql_command(config)
base_command(config, 'psql') + " -d #{config['database']}"
end
def dump_command(config)
base_command(config, 'pg_dump') + " -Fc #{config['database']}"
end
def raise_service_error
raise Error::Fail, 'Please check whether database service is up & running state.'
end
end
end
end