comparison sqlite_to_tabular.py @ 3:f079ea3884b3 draft default tip

planemo upload for repository https://github.com/jj-umn/galaxytools/tree/master/sqlite_to_tabular commit 64a950cafd655311c99a54f96a27b49f0bdf2731-dirty
author jjohnson
date Thu, 21 Jan 2016 09:34:45 -0500
parents bc50a7b7f246
children
comparison
equal deleted inserted replaced
2:bc50a7b7f246 3:f079ea3884b3
1 #!/usr/bin/env python 1 #!/usr/bin/env python
2 2
3 import sys 3 import sys
4 import re
4 import os.path 5 import os.path
5 import optparse 6 import optparse
6 import sqlite3 as sqlite 7 import sqlite3 as sqlite
7 8
9
10 def regex_match(expr, item):
11 return re.match(expr, item) is not None
12
13
14 def regex_search(expr, item):
15 return re.search(expr, item) is not None
16
17
18 def regex_sub(expr, replace, item):
19 return re.sub(expr, replace, item)
20
21
8 def __main__(): 22 def __main__():
9 #Parse Command Line 23 # Parse Command Line
10 parser = optparse.OptionParser() 24 parser = optparse.OptionParser()
11 parser.add_option( '-s', '--sqlitedb', dest='sqlitedb', default=None, help='The SQLite Database' ) 25 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' ) 26 parser.add_option('-q', '--query', dest='query', default=None, help='SQL query')
13 parser.add_option( '-Q', '--query_file', dest='query_file', default=None, help='SQL query file' ) 27 parser.add_option('-Q', '--query_file', dest='query_file', default=None, help='SQL query file')
14 parser.add_option( '-n', '--no_header', dest='no_header', action='store_true', default=False, help='Include a column headers line' ) 28 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' ) 29 parser.add_option('-o', '--output', dest='output', default=None, help='Output file for query results')
16 (options, args) = parser.parse_args() 30 (options, args) = parser.parse_args()
17 31
18 # determine output destination 32 # determine output destination
19 if options.output != None: 33 if options.output is not None:
34 try:
35 outputPath = os.path.abspath(options.output)
36 outputFile = open(outputPath, 'w')
37 except Exception, e:
38 print >> sys.stderr, "failed: %s" % e
39 exit(3)
40 else:
41 outputFile = sys.stdout
42
43 query = None
44 if (options.query_file is not None):
45 with open(options.query_file, 'r') as fh:
46 query = ''
47 for line in fh:
48 query += line
49 elif (options.query is not None):
50 query = options.query
51
52 if (query is None):
53 try:
54 conn = sqlite.connect(options.sqlitedb)
55 c = conn.cursor()
56 tables_query = "SELECT name,sql FROM sqlite_master WHERE type='table' ORDER BY name"
57 rslt = c.execute(tables_query).fetchall()
58 for table, sql in rslt:
59 print >> sys.stderr, "Table %s:" % table
60 try:
61 col_query = 'SELECT * FROM %s LIMIT 0' % table
62 cur = conn.cursor().execute(col_query)
63 cols = [col[0] for col in cur.description]
64 print >> sys.stderr, " Columns: %s" % cols
65 except Exception, exc:
66 print >> sys.stderr, "Error: %s" % exc
67 except Exception, exc:
68 print >> sys.stderr, "Error: %s" % exc
69 exit(0)
20 try: 70 try:
21 outputPath = os.path.abspath(options.output) 71 conn = sqlite.connect(options.sqlitedb)
22 outputFile = open(outputPath, 'w') 72 conn.create_function("re_match", 2, regex_match)
23 except Exception, e: 73 conn.create_function("re_search", 2, regex_search)
24 print >> sys.stderr, "failed: %s" % e 74 conn.create_function("re_sub", 3, regex_sub)
25 exit(3) 75 cur = conn.cursor()
26 else: 76 results = cur.execute(query)
27 outputFile = sys.stdout 77 if not options.no_header:
78 outputFile.write("#%s\n" % '\t'.join([str(col[0]) for col in cur.description]))
79 for i, row in enumerate(results):
80 outputFile.write("%s\n" % '\t'.join([str(val) for val in row]))
81 except Exception, exc:
82 print >> sys.stderr, "Error: %s" % exc
83 exit(1)
28 84
29 query = None 85 if __name__ == "__main__":
30 if (options.query_file != None): 86 __main__()
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):
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
55 exit(0)
56 #if not sqlite.is_read_only_query(query):
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()
62 results = cur.execute(query)
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