20
|
1 #!/usr/bin/env python
|
|
2
|
|
3 from __future__ import print_function
|
|
4
|
|
5 import optparse
|
|
6 import os.path
|
|
7 import sys
|
|
8
|
|
9 from query_db import describe_tables, get_connection, run_query
|
|
10
|
|
11
|
|
12 def __main__():
|
|
13 # Parse Command Line
|
|
14 parser = optparse.OptionParser()
|
|
15 parser.add_option('-s', '--sqlitedb', dest='sqlitedb', default=None,
|
|
16 help='The SQLite Database')
|
|
17 parser.add_option('-q', '--query', dest='query', default=None,
|
|
18 help='SQL query')
|
|
19 parser.add_option('-Q', '--query_file', dest='query_file', default=None,
|
|
20 help='SQL query file')
|
|
21 parser.add_option('-n', '--no_header', dest='no_header', default=False,
|
|
22 action='store_true',
|
|
23 help='Include a column headers line')
|
|
24 parser.add_option('-o', '--output', dest='output', default=None,
|
|
25 help='Output file for query results')
|
|
26 (options, args) = parser.parse_args()
|
|
27
|
|
28 # determine output destination
|
|
29 if options.output is not None:
|
|
30 try:
|
|
31 outputPath = os.path.abspath(options.output)
|
|
32 outputFile = open(outputPath, 'w')
|
|
33 except Exception as e:
|
|
34 print("failed: %s" % e, file=sys.stderr)
|
|
35 exit(3)
|
|
36 else:
|
|
37 outputFile = sys.stdout
|
|
38
|
|
39 query = None
|
|
40 if (options.query_file is not None):
|
|
41 with open(options.query_file, 'r') as fh:
|
|
42 query = ''
|
|
43 for line in fh:
|
|
44 query += line
|
|
45 elif (options.query is not None):
|
|
46 query = options.query
|
|
47
|
|
48 if (query is None):
|
|
49 try:
|
|
50 describe_tables(get_connection(options.sqlitedb), outputFile)
|
|
51 except Exception as exc:
|
|
52 print("Error: %s" % exc, file=sys.stderr)
|
|
53 exit(0)
|
|
54 else:
|
|
55 try:
|
|
56 run_query(get_connection(options.sqlitedb), query, outputFile,
|
|
57 no_header=options.no_header)
|
|
58 except Exception as exc:
|
|
59 print("Error: %s" % exc, file=sys.stderr)
|
|
60 exit(1)
|
|
61
|
|
62
|
|
63 if __name__ == "__main__":
|
|
64 __main__()
|