This repository has been archived by the owner on Sep 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvsqlcsv
executable file
·123 lines (103 loc) · 2.55 KB
/
vsqlcsv
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
#!/usr/bin/env python
import vertica_python, argparse, csv, getpass, sys
parser = argparse.ArgumentParser(description="Outputs vertica query results as proper CSV")
parser.add_argument(
"--host",
help="Database host (default: localhost)",
type=str,
default='localhost'
)
parser.add_argument(
'-p',
"--port",
help="Database port (default: 5433)",
type=int,
default=5433
)
parser.add_argument(
'-U',
dest='user',
help="Database user (default: {})".format(getpass.getuser()),
type=str,
default=getpass.getuser()
)
parser.add_argument(
'-w',
dest='password',
help="Database user password (default: None)",
type=str,
default=''
)
parser.add_argument(
'-c',
dest='command',
help="Command to execute. (can also be passed via STDIN)",
type=str,
)
parser.add_argument(
'-F',
dest='delimiter',
help="Field Separator (default: ,)",
type=str,
default=','
)
parser.add_argument(
'-Q',
dest='quote',
help="Field delimiter, quote (default: \")",
type=str,
default='"'
)
parser.add_argument(
'--header',
help="Output header",
action='store_true'
)
parser.add_argument(
'--quoting',
help="Quoting style",
type=lambda q: q if hasattr(csv, 'QUOTE_' + q.upper()) else 'minimal',
default='minimal',
choices=['none', 'minimal', 'nonnumeric', 'all']
)
parser.add_argument(
'--escape-char',
help="Escape character",
type=str,
default='\\'
)
parser.add_argument(
dest='dbname',
help="Database name",
type=str,
nargs=1
)
args = parser.parse_args()
# Enable passing the command via stdin
command = ''
if args.command is not None and args.command != '':
command = args.command
else:
command = sys.stdin.read()
conn_info = {'host': args.host, 'port': args.port, 'user': args.user, 'password': args.password, 'database': args.dbname[0]}
connection = None
try:
connection = vertica_python.connect(**conn_info)
cur = connection.cursor()
cur.execute(args.command)
writer = csv.writer(sys.stdout,
delimiter = args.delimiter,
quotechar = args.quote,
quoting = getattr(csv, 'QUOTE_' + args.quoting.upper()),
# This shouldn't be used. But we avoid exceptions by specifying this clause
escapechar = args.escape_char
)
if args.header:
writer.writerow(list(col.name for col in cur.description))
for row in cur.iterate():
writer.writerow(row)
except Exception as ex:
raise
finally:
if connection is not None:
connection.close()