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' )
|
|
13 parser.add_option( '-n', '--no_header', dest='no_header', action='store_true', default=False, help='Include a column headers line' )
|
|
14 parser.add_option( '-o', '--output', dest='output', default=None, help='Output file for query results' )
|
|
15 (options, args) = parser.parse_args()
|
|
16
|
|
17 # determine output destination
|
|
18 if options.output != None:
|
|
19 try:
|
|
20 outputPath = os.path.abspath(options.output)
|
|
21 outputFile = open(outputPath, 'w')
|
|
22 except Exception, e:
|
|
23 print >> sys.stderr, "failed: %s" % e
|
|
24 exit(3)
|
|
25 else:
|
|
26 outputFile = sys.stdout
|
|
27
|
|
28 if (options.query is None):
|
|
29 try:
|
|
30 conn = sqlite.connect(options.sqlitedb)
|
|
31 c = conn.cursor()
|
|
32 tables_query = "SELECT name,sql FROM sqlite_master WHERE type='table' ORDER BY name"
|
|
33 rslt = c.execute(tables_query).fetchall()
|
|
34 for table,sql in rslt:
|
|
35 print >> sys.stderr, "Table %s:" % table
|
|
36 try:
|
|
37 col_query = 'SELECT * FROM %s LIMIT 0' % table
|
|
38 cur = conn.cursor().execute(col_query)
|
|
39 cols = [col[0] for col in cur.description]
|
|
40 print >> sys.stderr, " Columns: %s" % cols
|
|
41 except Exception, exc:
|
|
42 print >> sys.stderr, "Error: %s" % exc
|
|
43 except Exception, exc:
|
|
44 print >> sys.stderr, "Error: %s" % exc
|
|
45 exit(1)
|
|
46 #if not sqlite.is_read_only_query(options.query):
|
|
47 # print >> sys.stderr, "Error: Must be a read only query"
|
|
48 # exit(2)
|
|
49 try:
|
|
50 conn = sqlite.connect(options.sqlitedb)
|
|
51 cur = conn.cursor()
|
|
52 results = cur.execute(options.query)
|
|
53 if not options.no_header:
|
|
54 outputFile.write("#%s\n" % '\t'.join([str(col[0]) for col in cur.description]))
|
|
55 # yield [col[0] for col in cur.description]
|
|
56 for i,row in enumerate(results):
|
|
57 # yield [val for val in row]
|
|
58 outputFile.write("%s\n" % '\t'.join([str(val) for val in row]))
|
|
59 except Exception, exc:
|
|
60 print >> sys.stderr, "Error: %s" % exc
|
|
61 exit(1)
|
|
62
|
|
63 if __name__ == "__main__": __main__()
|
|
64
|