annotate query_tabular.py @ 0:763c4f968dc6

Uploaded
author jjohnson
date Thu, 01 Oct 2015 09:50:16 -0400
parents
children 24f0911f75ee
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
0
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
1 #!/usr/bin/env python
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
2 """
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
3 """
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
4 import sys
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
5 import os.path
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
6 import sqlite3 as sqlite
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
7 import optparse
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
8 from optparse import OptionParser
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
9
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
10 """
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
11 TODO:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
12 - could add some transformations on tabular columns, e.g. a regex to format date/time strings
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
13 - allow multiple queries and outputs
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
14 - add a --json input for table definitions (or yaml)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
15 JSON config:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
16 { tables : [
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
17 { file_path : '/home/galaxy/dataset_101.dat',
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
18 table_name : 't1',
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
19 column_names : ['c1','c2','c3']
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
20 },
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
21 { file_path : '/home/galaxy/dataset_102.dat',
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
22 table_name : 't2',
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
23 column_names : ['c1','c2','c3']
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
24 }
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
25 ]
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
26 }
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
27 """
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
28
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
29 def getValueType(val):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
30 if val or 0. == val:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
31 try:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
32 int(val)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
33 return 'INTEGER'
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
34 except:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
35 try:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
36 float(val)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
37 return 'REAL'
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
38 except:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
39 return 'TEXT'
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
40 return None
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
41
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
42
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
43 def get_column_def(file_path,table_name,skip=0,comment_char='#',column_names=None,max_lines=100):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
44 col_pref = ['TEXT','REAL','INTEGER',None]
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
45 col_types = []
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
46 data_lines = 0
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
47 try:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
48 with open(file_path,"r") as fh:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
49 for linenum,line in enumerate(fh):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
50 if linenum < skip:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
51 continue
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
52 if line.startswith(comment_char):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
53 continue
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
54 data_lines += 1
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
55 try:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
56 fields = line.split('\t')
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
57 while len(col_types) < len(fields):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
58 col_types.append(None)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
59 for i,val in enumerate(fields):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
60 colType = getValueType(val)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
61 if col_pref.index(colType) < col_pref.index(col_types[i]):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
62 col_types[i] = colType
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
63 except Exception, e:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
64 print >> sys.stderr, 'Failed at line: %d err: %s' % (linenum,e)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
65 except Exception, e:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
66 print >> sys.stderr, 'Failed: %s' % (e)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
67 for i,col_type in enumerate(col_types):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
68 if not col_type:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
69 col_types[i] = 'TEXT'
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
70 col_names = ['c%d' % i for i in range(1,len(col_types) + 1)]
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
71 if column_names:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
72 for i,cname in enumerate([cn.strip() for cn in column_names.split(',')]):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
73 if cname and i < len(col_names):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
74 col_names[i] = cname
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
75 col_def = []
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
76 for i,col_name in enumerate(col_names):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
77 col_def.append('%s %s' % (col_names[i],col_types[i]))
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
78 return col_names,col_types,col_def
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
79
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
80 def create_table(conn,file_path,table_name,skip=0,comment_char='#',column_names=None):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
81 col_names,col_types,col_def = get_column_def(file_path,table_name,skip=skip,comment_char=comment_char,column_names=column_names)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
82 col_func = [float if t == 'REAL' else int if t == 'INTEGER' else str for t in col_types]
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
83 table_def = 'CREATE TABLE %s (\n %s\n);' % (table_name,',\n '.join(col_def))
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
84 # print >> sys.stdout, table_def
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
85 insert_stmt = 'INSERT INTO %s(%s) VALUES(%s)' % (table_name,','.join(col_names),','.join([ "?" for x in col_names]))
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
86 # print >> sys.stdout, insert_stmt
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
87 data_lines = 0
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
88 try:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
89 c = conn.cursor()
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
90 c.execute(table_def)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
91 with open(file_path,"r") as fh:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
92 for linenum,line in enumerate(fh):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
93 if linenum < skip or line.startswith(comment_char):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
94 continue
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
95 data_lines += 1
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
96 try:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
97 fields = line.split('\t')
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
98 vals = [col_func[i](x) if x else None for i,x in enumerate(fields)]
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
99 c.execute(insert_stmt,vals)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
100 except Exception, e:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
101 print >> sys.stderr, 'Failed at line: %d err: %s' % (linenum,e)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
102 conn.commit()
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
103 c.close()
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
104 except Exception, e:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
105 print >> sys.stderr, 'Failed: %s' % (e)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
106
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
107 def __main__():
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
108 #Parse Command Line
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
109 parser = optparse.OptionParser()
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
110 parser.add_option( '-s', '--sqlitedb', dest='sqlitedb', default=None, help='The SQLite Database' )
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
111 parser.add_option( '-t', '--table', dest='tables', action="append", default=[], help='Tabular file: file_path[=table_name[:column_name,...]' )
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
112 parser.add_option( '-q', '--query', dest='query', default=None, help='SQL query' )
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
113 parser.add_option( '-n', '--no_header', dest='no_header', action='store_true', default=False, help='Include a column headers line' )
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
114 parser.add_option( '-o', '--output', dest='output', default=None, help='Output file for query results' )
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
115 (options, args) = parser.parse_args()
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
116
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
117 # oprn sqlite connection
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
118 conn = sqlite.connect(options.sqlitedb)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
119 # determine output destination
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
120 if options.output != None:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
121 try:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
122 outputPath = os.path.abspath(options.output)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
123 outputFile = open(outputPath, 'w')
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
124 except Exception, e:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
125 print >> sys.stderr, "failed: %s" % e
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
126 exit(3)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
127 else:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
128 outputFile = sys.stdout
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
129
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
130 # determine output destination
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
131 for ti,table in enumerate(options.tables):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
132 table_name = 't%d' % (ti + 1)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
133 column_names = None
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
134 fields = table.split('=')
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
135 path = fields[0]
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
136 if len(fields) > 1:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
137 names = fields[1].split(':')
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
138 table_name = names[0] if names[0] else table_name
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
139 if len(names) > 1:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
140 column_names = names[1]
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
141 # print >> sys.stdout, '%s %s' % (table_name, path)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
142 create_table(conn,path,table_name,column_names=column_names)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
143 conn.close()
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
144
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
145 if (options.query is None):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
146 try:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
147 conn = sqlite.connect(options.sqlitedb)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
148 c = conn.cursor()
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
149 tables_query = "SELECT name,sql FROM sqlite_master WHERE type='table' ORDER BY name"
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
150 rslt = c.execute(tables_query).fetchall()
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
151 for table,sql in rslt:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
152 print >> sys.stderr, "Table %s:" % table
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
153 try:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
154 col_query = 'SELECT * FROM %s LIMIT 0' % table
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
155 cur = conn.cursor().execute(col_query)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
156 cols = [col[0] for col in cur.description]
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
157 print >> sys.stderr, " Columns: %s" % cols
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
158 except Exception, exc:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
159 print >> sys.stderr, "Error: %s" % exc
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
160 except Exception, exc:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
161 print >> sys.stderr, "Error: %s" % exc
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
162 exit(0)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
163 #if not sqlite.is_read_only_query(options.query):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
164 # print >> sys.stderr, "Error: Must be a read only query"
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
165 # exit(2)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
166 try:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
167 conn = sqlite.connect(options.sqlitedb)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
168 cur = conn.cursor()
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
169 results = cur.execute(options.query)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
170 if not options.no_header:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
171 outputFile.write("#%s\n" % '\t'.join([str(col[0]) for col in cur.description]))
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
172 # yield [col[0] for col in cur.description]
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
173 for i,row in enumerate(results):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
174 # yield [val for val in row]
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
175 outputFile.write("%s\n" % '\t'.join([str(val) for val in row]))
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
176 except Exception, exc:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
177 print >> sys.stderr, "Error: %s" % exc
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
178
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
179 if __name__ == "__main__": __main__()
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
180
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
181