annotate query_tabular.py @ 2:ffa5e34a55c1

Uploaded
author jjohnson
date Sun, 04 Oct 2015 10:52:21 -0400
parents 24f0911f75ee
children 125fc5d123b3 afdbc7198353
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)
1
24f0911f75ee Uploaded
jjohnson
parents: 0
diff changeset
106 exit(1)
0
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
107
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
108 def __main__():
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
109 #Parse Command Line
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
110 parser = optparse.OptionParser()
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
111 parser.add_option( '-s', '--sqlitedb', dest='sqlitedb', default=None, help='The SQLite Database' )
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
112 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
113 parser.add_option( '-q', '--query', dest='query', default=None, help='SQL query' )
2
ffa5e34a55c1 Uploaded
jjohnson
parents: 1
diff changeset
114 parser.add_option( '-Q', '--query_file', dest='query_file', default=None, help='SQL query file' )
0
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
115 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
116 parser.add_option( '-o', '--output', dest='output', default=None, help='Output file for query results' )
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
117 (options, args) = parser.parse_args()
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
118
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
119 # oprn sqlite connection
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
120 conn = sqlite.connect(options.sqlitedb)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
121 # determine output destination
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
122 if options.output != None:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
123 try:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
124 outputPath = os.path.abspath(options.output)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
125 outputFile = open(outputPath, 'w')
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
126 except Exception, e:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
127 print >> sys.stderr, "failed: %s" % e
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
128 exit(3)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
129 else:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
130 outputFile = sys.stdout
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
131
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
132 # determine output destination
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
133 for ti,table in enumerate(options.tables):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
134 table_name = 't%d' % (ti + 1)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
135 column_names = None
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
136 fields = table.split('=')
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
137 path = fields[0]
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
138 if len(fields) > 1:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
139 names = fields[1].split(':')
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
140 table_name = names[0] if names[0] else table_name
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
141 if len(names) > 1:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
142 column_names = names[1]
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
143 # print >> sys.stdout, '%s %s' % (table_name, path)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
144 create_table(conn,path,table_name,column_names=column_names)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
145 conn.close()
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
146
2
ffa5e34a55c1 Uploaded
jjohnson
parents: 1
diff changeset
147 query = None
ffa5e34a55c1 Uploaded
jjohnson
parents: 1
diff changeset
148 if (options.query_file != None):
ffa5e34a55c1 Uploaded
jjohnson
parents: 1
diff changeset
149 with open(options.query_file,'r') as fh:
ffa5e34a55c1 Uploaded
jjohnson
parents: 1
diff changeset
150 query = ''
ffa5e34a55c1 Uploaded
jjohnson
parents: 1
diff changeset
151 for line in fh:
ffa5e34a55c1 Uploaded
jjohnson
parents: 1
diff changeset
152 query += line
ffa5e34a55c1 Uploaded
jjohnson
parents: 1
diff changeset
153 elif (options.query != None):
ffa5e34a55c1 Uploaded
jjohnson
parents: 1
diff changeset
154 query = options.query
ffa5e34a55c1 Uploaded
jjohnson
parents: 1
diff changeset
155
ffa5e34a55c1 Uploaded
jjohnson
parents: 1
diff changeset
156 if (query is None):
0
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
157 try:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
158 conn = sqlite.connect(options.sqlitedb)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
159 c = conn.cursor()
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
160 tables_query = "SELECT name,sql FROM sqlite_master WHERE type='table' ORDER BY name"
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
161 rslt = c.execute(tables_query).fetchall()
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
162 for table,sql in rslt:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
163 print >> sys.stderr, "Table %s:" % table
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
164 try:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
165 col_query = 'SELECT * FROM %s LIMIT 0' % table
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
166 cur = conn.cursor().execute(col_query)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
167 cols = [col[0] for col in cur.description]
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
168 print >> sys.stderr, " Columns: %s" % cols
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
169 except Exception, exc:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
170 print >> sys.stderr, "Error: %s" % exc
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
171 except Exception, exc:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
172 print >> sys.stderr, "Error: %s" % exc
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
173 exit(0)
2
ffa5e34a55c1 Uploaded
jjohnson
parents: 1
diff changeset
174 #if not sqlite.is_read_only_query(query):
0
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
175 # print >> sys.stderr, "Error: Must be a read only query"
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
176 # exit(2)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
177 try:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
178 conn = sqlite.connect(options.sqlitedb)
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
179 cur = conn.cursor()
2
ffa5e34a55c1 Uploaded
jjohnson
parents: 1
diff changeset
180 results = cur.execute(query)
0
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
181 if not options.no_header:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
182 outputFile.write("#%s\n" % '\t'.join([str(col[0]) for col in cur.description]))
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
183 # yield [col[0] for col in cur.description]
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
184 for i,row in enumerate(results):
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
185 # yield [val for val in row]
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
186 outputFile.write("%s\n" % '\t'.join([str(val) for val in row]))
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
187 except Exception, exc:
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
188 print >> sys.stderr, "Error: %s" % exc
1
24f0911f75ee Uploaded
jjohnson
parents: 0
diff changeset
189 exit(1)
0
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
190
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
191 if __name__ == "__main__": __main__()
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
192
763c4f968dc6 Uploaded
jjohnson
parents:
diff changeset
193