0
|
1 #!/usr/bin/env python
|
|
2
|
|
3 import sys
|
|
4 import os.path
|
|
5 import optparse
|
|
6 import sqlite3 as sqlite
|
|
7
|
|
8 def __main__():
|
|
9 #Parse Command Line
|
|
10 parser = optparse.OptionParser()
|
|
11 parser.add_option( '-s', '--sqlitedb', dest='sqlitedb', default=None, help='The SQLite Database' )
|
|
12 parser.add_option( '-q', '--query', dest='query', default=None, help='SQL query' )
|
2
|
13 parser.add_option( '-Q', '--query_file', dest='query_file', default=None, help='SQL query file' )
|
0
|
14 parser.add_option( '-n', '--no_header', dest='no_header', action='store_true', default=False, help='Include a column headers line' )
|
|
15 parser.add_option( '-o', '--output', dest='output', default=None, help='Output file for query results' )
|
|
16 (options, args) = parser.parse_args()
|
|
17
|
|
18 # determine output destination
|
|
19 if options.output != None:
|
|
20 try:
|
|
21 outputPath = os.path.abspath(options.output)
|
|
22 outputFile = open(outputPath, 'w')
|
|
23 except Exception, e:
|
|
24 print >> sys.stderr, "failed: %s" % e
|
|
25 exit(3)
|
|
26 else:
|
|
27 outputFile = sys.stdout
|
|
28
|
2
|
29 query = None
|
|
30 if (options.query_file != None):
|
|
31 with open(options.query_file,'r') as fh:
|
|
32 query = ''
|
|
33 for line in fh:
|
|
34 query += line
|
|
35 elif (options.query != None):
|
|
36 query = options.query
|
|
37
|
|
38 if (query is None):
|
0
|
39 try:
|
|
40 conn = sqlite.connect(options.sqlitedb)
|
|
41 c = conn.cursor()
|
|
42 tables_query = "SELECT name,sql FROM sqlite_master WHERE type='table' ORDER BY name"
|
|
43 rslt = c.execute(tables_query).fetchall()
|
|
44 for table,sql in rslt:
|
|
45 print >> sys.stderr, "Table %s:" % table
|
|
46 try:
|
|
47 col_query = 'SELECT * FROM %s LIMIT 0' % table
|
|
48 cur = conn.cursor().execute(col_query)
|
|
49 cols = [col[0] for col in cur.description]
|
|
50 print >> sys.stderr, " Columns: %s" % cols
|
|
51 except Exception, exc:
|
|
52 print >> sys.stderr, "Error: %s" % exc
|
|
53 except Exception, exc:
|
|
54 print >> sys.stderr, "Error: %s" % exc
|
2
|
55 exit(0)
|
|
56 #if not sqlite.is_read_only_query(query):
|
0
|
57 # print >> sys.stderr, "Error: Must be a read only query"
|
|
58 # exit(2)
|
|
59 try:
|
|
60 conn = sqlite.connect(options.sqlitedb)
|
|
61 cur = conn.cursor()
|
2
|
62 results = cur.execute(query)
|
0
|
63 if not options.no_header:
|
|
64 outputFile.write("#%s\n" % '\t'.join([str(col[0]) for col in cur.description]))
|
|
65 # yield [col[0] for col in cur.description]
|
|
66 for i,row in enumerate(results):
|
|
67 # yield [val for val in row]
|
|
68 outputFile.write("%s\n" % '\t'.join([str(val) for val in row]))
|
|
69 except Exception, exc:
|
|
70 print >> sys.stderr, "Error: %s" % exc
|
|
71 exit(1)
|
|
72
|
|
73 if __name__ == "__main__": __main__()
|
|
74
|