forked from machacekondra/python-rrmngmnt
-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathdb.py
80 lines (70 loc) · 2.31 KB
/
db.py
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
from rrmngmnt.service import Service
class Database(Service):
def __init__(self, host, name, user):
"""
Args:
host (Host): Remote resouce to DB machine
name (str): database name
user (User): user/role
"""
super(Database, self).__init__(host)
self.name = name
self.user = user
def psql(self, sql, *args):
"""
Execute sql command on host
Args:
sql (str): sql command
args (list): positional format arguments for command
Returns:
list: list of lines with records.
"""
separator = '__RECORD_SEPARATOR__'
sql = sql % tuple(args)
cmd = [
'export', 'PGPASSWORD=%s;' % self.user.password,
'psql', '-d', self.name, '-U', self.user.name, '-h', 'localhost',
'-R', separator, '-t', '-A', '-c', sql,
]
executor = self.host.executor()
with executor.session() as ss:
rc, out, err = ss.run_cmd(cmd)
if rc:
raise Exception(
"Failed to exec sql command: %s" % err
)
return [
a.strip().split('|') for a in out.strip().split(separator)
if a.strip()
]
# NOTE: I am considering to use Psycopg2 to access DB directly.
# I need to think whether it is better or not.
# We need to realize that connection can be forbidden from outside ...
def psql_cmd(self, command):
"""
Execute psql special command on host (e.g. \\dt, \\dv, ...)
Args:
command (str): special psql command
Returns:
str: output of the command
"""
cmd = [
'export', 'PGPASSWORD=%s;' % self.user.password,
'psql', '-d', self.name, '-U', self.user.name, '-h', 'localhost',
'-c', command
]
executor = self.host.executor()
with executor.session() as ss:
rc, out, err = ss.run_cmd(cmd)
if rc:
raise Exception(
"Failed to exec command: %s" % err
)
if not out and err:
out = err
return out
def restart(self):
"""
Restart postgresql service
"""
self.host.service('postgresql').restart()