-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
81 lines (60 loc) · 1.96 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
81
#/bin/env python
""" Database functions """
import os
import os.path as path
import sys
import re
import psycopg2
import dictconfig
# database connection. Will be set when necessary.
CONNECTION = None
def connection_args():
"""Reads config/database.yml returns the database configuration
matching RAILS_ENV value"""
app_config = dictconfig.parse()
env = app_config['database.environment'] + ':'
db_config = path.join(path.dirname(path.abspath(sys.argv[0])), app_config['database.configfile'])
# maps yaml key names to postgres connection names
fields = {
'database': 'dbname',
'username': 'user',
'password': 'password',
'host': 'host',
}
data = []
found = False
with open(db_config) as f:
for line in f:
line = line.strip()
if line == env:
found = True
elif found and not line:
break
else:
match = re.search('(\w+):\s*(.+)$', line)
if match:
try:
key = fields[match.group(1)]
data.append('%s=%s' % (key, match.group(2)))
except KeyError:
pass
return ' '.join(data)
def connection():
"""Stores and returns a handle to the database"""
global CONNECTION
#TODO -- check for lost connection and retry...
if not CONNECTION:
CONNECTION = psycopg2.connect(connection_args())
return CONNECTION
def cursor():
"""..."""
return connection().cursor()
def dict_to_sql_insert(tablename, data):
"""constructs and returns a pair of string and data to be
handed off to sql.execute"""
values = data.values()
query = "INSERT INTO %s (%s) VALUES (%s) RETURNING lastval()" % \
(tablename, ', '.join(data.keys()), ', '.join(['%s'] * len(values)))
return [query, values]
if __name__ == "__main__":
print connection_args()