forked from Som-Energia/somenergia-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql2csv.py
executable file
·71 lines (56 loc) · 1.69 KB
/
sql2csv.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
#!/usr/bin/env python
#-*- coding: utf8 -*-
import psycopg2
import dbutils
import sys
from consolemsg import step, error, fail, warn
from yamlns import namespace as ns
def main():
options = ns()
optarg = None
cliargs = ns()
keyarg = None
args = []
for arg in sys.argv[1:]:
if keyarg:
cliargs[keyarg]=eval(arg) if arg.startswith("(") else arg
keyarg=None
continue
if optarg:
options[optarg]=arg
optarg=None
continue
if arg.startswith('--'):
keyarg = arg[2:]
continue
if arg.startswith('-'):
optarg = arg[1:]
continue
args.append(arg)
if not args:
fail("Argument required. Usage:\n"
"{} <sqlfile> [-C <dbconfig.py>] [<yamlfile>] [--<var1> <value1> [--<var2> <value2> ..] ]".format(sys.argv[0]))
step("Loading {}...".format(args[0]))
with open(args[0]) as sqlfile:
query = sqlfile.read()
variables = ns()
if len(args)>=2:
step("Loading variables...".format(args[1]))
variables = ns.load(args[1])
warn(variables.dump())
variables.update(cliargs)
if 'C' in options:
import imp
config=imp.load_source('config',options.C)
else:
import config
step("Connecting to the database...")
db = psycopg2.connect(**config.psycopg)
with db.cursor() as cursor :
try:
cursor.execute(query, variables)
except KeyError as e:
fail("Missing variable '{key}'. Specify it in the YAML file or by using the --{key} option"
.format(key=e.args[0]))
print dbutils.csvTable(cursor)
main()