-
Notifications
You must be signed in to change notification settings - Fork 3
/
pg.py
executable file
·151 lines (116 loc) · 3.73 KB
/
pg.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
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
#!/usr/bin/python3
import argparse
import logging
import psycopg2
import config
def connect_string(with_password=True):
'''
Returns postgresql connection string suitable for use in psycopg connect
and in psql
'''
# some default values:
connect_params = {
# Maximum time to wait while connecting, in seconds.
# Zero, negative, or not specified means wait indefinitely.
'connect_timeout': 10,
# seconds of inactivity after which TCP should send a keepalive
# message to the server
'keepalives_idle': 10,
# the number of seconds after which a TCP keepalive message that is
# not acknowledged by the server should be retransmitted
'keepalives_interval': 10,
# the number of TCP keepalives that can be lost before the client's
# connection to the server is considered dead
'keepalives_count': 3,
}
pg_cfg = config.get_section('postgresql')
host = pg_cfg.get('host', None)
if host:
connect_params['host'] = host
port = pg_cfg.get('port', None)
if port:
connect_params['post'] = port
user = pg_cfg.get('user', None)
if user:
connect_params['user'] = user
if with_password:
password = pg_cfg.get('password', None)
if password:
connect_params['password'] = password
dbname = pg_cfg.get('db', None)
if dbname:
connect_params['dbname'] = dbname
return ' '.join(
k + '=' + str(v)
for k, v in connect_params.items())
def get_conn():
'''
Return *the* common psycopg connection to the database
based on config
'''
global __pg_connection
try:
return __pg_connection
except NameError:
logger = logging.getLogger(__name__)
logger.debug('Opening new connection to postgres')
__pg_connection = psycopg2.connect(connect_string())
return __pg_connection
def cursor():
'''
Simple wrapper around cursor() for the one connection
'''
return get_conn().cursor()
def commit():
'''
Simple wrapper around commit for the one connection
'''
return get_conn().commit()
def set_autocommit(autocommit):
'''
Simple wrapper to set autocommit mode
See https://www.psycopg.org/docs/usage.html#transactions-control
'''
conn = get_conn()
conn.set_session(autocommit=autocommit)
def escape_str(text):
'''
Quote a text, doubling the quote when needed
'''
return "'" + text.replace("'", "''") + "'"
def escape_name(name):
'''
if DB_QUOTE_NAMES is set in config, quote the name
'''
assert '"' not in name
if config.DB_QUOTE_NAMES:
return '"' + name + '"'
return name
def table_name(name, schema=None):
'''
leave schema empty for using config
usage is temporary tables ( psycopg2.errors.InvalidTableDefinition:
cannot create temporary relation in non-temporary schema)
'''
if schema is None:
schema = config.DB_SCHEMA
if schema:
result = escape_name(schema)
result += '.'
else:
result = ''
result += escape_name(name)
return result
if __name__ == '__main__':
def main():
parser = argparse.ArgumentParser(
description='Print postgres connection string from config')
parser.parse_args()
logging.basicConfig(
filename=config.LOGFILE,
format=config.LOGFORMAT.format('pg'),
level=config.LOGLEVEL)
# You don't want to print your password. Ever.
# Create a ~/.pgpass file if you need non-interractive work.
print(connect_string(with_password=False))
main()