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:
|
22
|
34 exit('Error: %s' % (e))
|
20
|
35 else:
|
|
36 outputFile = sys.stdout
|
|
37
|
|
38 query = None
|
|
39 if (options.query_file is not None):
|
|
40 with open(options.query_file, 'r') as fh:
|
|
41 query = ''
|
|
42 for line in fh:
|
|
43 query += line
|
|
44 elif (options.query is not None):
|
|
45 query = options.query
|
|
46
|
|
47 if (query is None):
|
|
48 try:
|
|
49 describe_tables(get_connection(options.sqlitedb), outputFile)
|
22
|
50 except Exception as e:
|
|
51 exit('Error: %s' % (e))
|
20
|
52 exit(0)
|
|
53 else:
|
|
54 try:
|
|
55 run_query(get_connection(options.sqlitedb), query, outputFile,
|
|
56 no_header=options.no_header)
|
22
|
57 except Exception as e:
|
|
58 exit('Error: %s' % (e))
|
20
|
59
|
|
60
|
|
61 if __name__ == "__main__":
|
|
62 __main__()
|