make statev_sql commandlines similar to mysql commandlines
[libfirm] / scripts / statev_sql.py
1 #! /usr/bin/env python
2
3 import sys
4 import os
5 import re
6 import time
7 import stat
8 import fileinput
9 import tempfile
10 import optparse
11
12 class DummyFilter:
13         def match(self, dummy):
14                 return True
15
16 class EmitBase:
17         ctx_field_ids = {}
18         ev_field_ids = {}
19         types = {}
20
21         def create_table(self, cols, name, defaulttype, keytype, extra=""):
22                 c  = "create table if not exists `%s` (\n" % name
23                 c += "\t`id` %s\n" % keytype
24
25                 for x in cols:
26                         name = x
27                         type = self.types[defaulttype]
28                         if x[0] == '$':
29                                 name = x[1:]
30                                 type = self.types["text"]
31                         elif x[0] == '?':
32                                 name = x[1:]
33                                 type = self.types["bool"]
34
35                         c += "\t,`%s` %s\n" % (name, type)
36                 c += extra
37                 c += ");"
38                 self.execute(c)
39
40 # Abstraction for mysql sql connection and sql syntax
41 class EmitMysql(EmitBase):
42         tmpfile_mode = stat.S_IREAD | stat.S_IROTH | stat.S_IWUSR
43
44         def execute(self, query, *args):
45                 #print query + " %s\n" % str(tuple(args))
46                 self.cursor.execute(query, *args);
47                 self.conn.commit()
48
49         def connect(self, options):
50                 import MySQLdb
51
52                 args = dict()
53                 if options.password:
54                         args['passwd'] = options.password
55                 if not options.host:
56                         options.host = 'localhost'
57                 args['user'] = options.user
58                 args['host'] = options.host
59                 args['db']   = options.database
60
61                 self.conn     = MySQLdb.connect(**args)
62                 self.options  = options
63                 self.cursor   = self.conn.cursor()
64
65         def __init__(self, options, ctxcols, evcols):
66                 self.connect(options)
67
68                 self.types["text"] = "varchar(80) default null";
69                 self.types["data"] = "double default null";
70                 self.types["bool"] = "bool";
71
72                 self.ctxtab = options.prefix + "ctx"
73                 self.evtab  = options.prefix + "ev"
74
75                 if not options.update:
76                         self.execute('drop table if exists `%s`' % self.evtab)
77                         self.execute('drop table if exists `%s`' % self.ctxtab)
78
79                 self.create_table(ctxcols, self.ctxtab, "text", "int auto_increment", extra = ", PRIMARY KEY (`id`)")
80                 self.create_table(evcols, self.evtab, "data", "int not null", extra = ", INDEX(`id`)")
81
82                 keys  = "id, " + ", ".join(evcols)
83                 marks = ",".join(['%s'] * (len(evcols)+1))
84                 self.evinsert = "insert into `%s` values (%s)" % (self.evtab, marks)
85
86                 keys  = ", ".join(ctxcols)
87                 marks = ",".join(['%s'] * len(ctxcols))
88                 self.ctxinsert = "insert into `%s` (%s) values (%s)" % (self.ctxtab, keys, marks)
89
90         def ev(self, curr_id, evitems):
91                 self.execute(self.evinsert, (curr_id,) + tuple(evitems))
92
93         def ctx(self, ctxitems):
94                 self.execute(self.ctxinsert, tuple(ctxitems))
95                 self.conn.commit()
96                 id = self.cursor.lastrowid
97                 return id
98
99         def commit(self):
100                 self.conn.commit()
101
102 # Abstraction for sqlite3 databases and sql syntax
103 class EmitSqlite3(EmitBase):
104         def execute(self, query, *args):
105                 #print query + " %s\n" % str(tuple(args))
106                 self.cursor.execute(query, *args)
107
108         def __init__(self, options, ctxcols, evcols):
109                 import sqlite3
110
111                 if options.database == None:
112                         print "Have to specify database (file-)name for sqlite"
113                         sys.exit(1)
114
115                 if not options.update:
116                         if os.path.isfile(options.database):
117                                 os.unlink(options.database)
118
119                 self.conn = sqlite3.connect(options.database)
120                 self.cursor = self.conn.cursor()
121
122                 self.types["data"] = "double"
123                 self.types["text"] = "text"
124                 self.types["bool"] = "int"
125                 self.ctxtab = options.prefix + "ctx"
126                 self.evtab  = options.prefix + "ev"
127
128                 self.create_table(ctxcols, self.ctxtab, "text", "integer primary key")
129                 self.create_table(evcols, self.evtab, "data", "int")
130                 self.execute("CREATE INDEX IF NOT EXISTS `%sindex` ON `%s`(id)"
131                                 % (self.evtab, self.evtab))
132
133                 keys  = "id, " + ", ".join(evcols)
134                 marks = ",".join(["?"] * (len(evcols)+1))
135                 self.evinsert = "insert into `%s` values (%s)" % (self.evtab, marks)
136
137                 keys  = ", ".join(ctxcols)
138                 marks = ",".join(["?"] * len(ctxcols))
139                 self.ctxinsert = "insert into `%s` (%s) values (%s)" % (self.ctxtab, keys, marks)
140
141                 self.nextid = 0
142
143         def ev(self, curr_id, evitems):
144                 self.execute(self.evinsert, (curr_id,) + tuple(evitems))
145
146         def ctx(self, ctxitems):
147                 curr_id = self.nextid
148                 self.nextid += 1
149                 self.execute(self.ctxinsert, tuple(ctxitems))
150                 self.conn.commit()
151                 return self.cursor.lastrowid
152
153         def commit(self):
154                 self.conn.commit()
155
156 class Conv:
157         engines = { 'sqlite3': EmitSqlite3, 'mysql': EmitMysql }
158
159         # Pass that determines event and context types
160         def find_heads(self):
161                 n_ev    = 0
162                 ctxind  = 0
163                 evind   = 0
164                 ctxcols = dict()
165                 evcols  = dict()
166                 linenr  = 0
167
168                 self.valid_keys = set()
169
170                 inp = self.input()
171
172                 for line in inp:
173                         linenr += 1
174                         fields  = line.strip().split(";")
175                         if fields[0] == 'P':
176                                 if (len(fields)-1) % 2 != 0:
177                                         print "%s: Invalid number of fields after 'P'" % linenr
178
179                                 for i in range(1,len(fields),2):
180                                         key = fields[i]
181                                         if not ctxcols.has_key(key):
182                                                 ctxcols[key] = ctxind
183                                                 ctxind += 1
184
185                         elif fields[0] == 'E':
186                                 if (len(fields)-1) % 2 != 0:
187                                         print "%s: Invalid number of fields after 'E'" % linenr
188
189                                 self.n_events += 1
190                                 for i in range(1,len(fields),2):
191                                         key = fields[i]
192                                         if not self.filter.match(key):
193                                                 continue
194
195                                         if not evcols.has_key(key):
196                                                 self.valid_keys.add(key)
197                                                 evcols[key] = evind
198                                                 evind += 1
199
200                 self.ctxcols = ctxcols
201                 self.evcols = evcols
202                 return (ctxcols, evcols)
203
204         def input(self):
205                 return fileinput.FileInput(files=self.files, openhook=fileinput.hook_compressed)
206
207         def flush_events(self, id):
208                 isnull = True
209                 for e in self.evvals:
210                         if e != None:
211                                 isnull = False
212                                 break
213                 if isnull:
214                         return
215
216                 self.emit.ev(id, self.evvals)
217                 self.evvals = [None] * len(self.evvals)
218
219         def flush_ctx(self):
220                 if not self.pushpending:
221                         return
222                 self.pushpending = False
223                 self.curr_id = self.emit.ctx(self.ctxvals)
224
225         def fill_tables(self):
226                 lineno     = 0
227                 ids        = 0
228                 self.curr_id = -1
229                 keystack   = []
230                 idstack    = []
231                 curr_event = 0
232                 last_prec  = -1
233                 self.pushpending = False
234                 self.ctxvals = [None] * len(self.ctxcols)
235                 self.evvals  = [None] * len(self.evcols)
236
237                 for line in self.input():
238                         lineno += 1
239                         items   = line.strip().split(';')
240                         op      = items[0]
241
242                         # Push context command
243                         if op == 'P':
244                                 self.flush_events(self.curr_id)
245
246                                 # push the keys
247                                 for p in range(1,len(items),2):
248                                         key = items[p]
249                                         val = items[p+1]
250
251                                         keystack.append(key)
252                                         idstack.append(self.curr_id)
253
254                                         keyidx = self.ctxcols[key]
255                                         assert self.ctxvals[keyidx] == None
256                                         self.ctxvals[keyidx] = val
257                                 self.pushpending = True
258
259                         # Pop context command
260                         elif op == 'O':
261
262                                 # For now... we could optimize this
263                                 self.flush_ctx()
264
265                                 # We process fields in reverse order to makes O's match the
266                                 # order of previous P's
267                                 for p in range(len(items)-1,0,-1):
268                                         self.flush_events(self.curr_id)
269
270                                         popkey  = items[p]
271                                         key     = keystack.pop()
272                                         self.curr_id = idstack.pop()
273
274                                         if popkey != key:
275                                                 print "unmatched pop in line %d, push key %s, pop key: %s" % (lineno, key, popkey)
276
277                                         keyidx = self.ctxcols[key]
278                                         assert self.ctxvals[keyidx] != None
279                                         self.ctxvals[keyidx] = None
280
281                         elif op == 'E':
282                                 curr_event += 1
283
284                                 self.flush_ctx()
285
286                                 # Show that we make progress
287                                 if self.verbose:
288                                         prec = curr_event * 10 / self.n_events
289                                         if prec > last_prec:
290                                                 last_prec = prec
291                                                 print '%10d / %10d' % (curr_event, self.n_events)
292
293                                 for p in range(1,len(items),2):
294                                         key   = items[p]
295                                         if key not in self.evcols:
296                                                 continue
297
298                                         keyidx = self.evcols[key]
299                                         if self.evvals[keyidx] != None:
300                                                 self.flush_events(self.curr_id)
301
302                                         value          = items[p+1]
303                                         self.evvals[keyidx] = value
304
305         def __init__(self):
306                 parser = optparse.OptionParser('usage: %prog [options]  <event file...>')
307                 parser.add_option("", "--update",   dest="update",   help="update database instead of dropping all existing values", action="store_true", default=False)
308                 parser.add_option("-v", "--verbose",  dest="verbose",  help="verbose messages",         action="store_true", default=False)
309                 parser.add_option("-f", "--filter",   dest="filter",   help="regexp to filter event keys", metavar="REGEXP")
310                 parser.add_option("-u", "--user",     dest="user",     help="user",               metavar="USER")
311                 parser.add_option("-h", "--host",     dest="host",     help="host",               metavar="HOST")
312                 parser.add_option("-p", "--password", dest="password", help="password",           metavar="PASSWORD")
313                 parser.add_option("-D", "--database", dest="database", help="database",           metavar="DB")
314                 parser.add_option("-e", "--engine",   dest="engine",   help="engine (sqlite3, mysql)",             metavar="ENG", default='sqlite3')
315                 parser.add_option("-P", "--prefix",   dest="prefix",   help="table prefix",       metavar="PREFIX", default='')
316                 (options, args) = parser.parse_args()
317
318                 self.n_events = 0
319                 self.stmts    = dict()
320                 self.verbose  = options.verbose
321
322                 if len(args) < 1:
323                         parser.print_help()
324                         sys.exit(1)
325
326                 self.files  = []
327                 files       = args
328
329                 for file in files:
330                         if not os.path.isfile(file):
331                                 print "cannot find input file %s" % (file, )
332                         else:
333                                 self.files.append(file)
334
335                 if len(self.files) < 1:
336                         print "no input file to process"
337                         sys.exit(3)
338
339                 if options.filter:
340                         self.filter = re.compile(options.filter)
341                 else:
342                         self.filter = DummyFilter()
343
344                 if options.engine in self.engines:
345                         engine = self.engines[options.engine]
346                 else:
347                         print 'engine %s not found' % options.engine
348                         print 'we offer: %s' % self.engines.keys()
349                         sys.exit(0)
350
351                 if options.verbose:
352                         print "determining schema..."
353
354                 (ctxcols, evcols) = self.find_heads()
355                 if options.verbose:
356                         print "context schema:"
357                         print ctxcols
358                         print "event schema:"
359                         print evcols
360
361                 self.emit = engine(options, ctxcols, evcols)
362
363                 if options.verbose:
364                         print "filling tables..."
365                 self.fill_tables()
366                 if options.verbose:
367                         print "comitting..."
368                 self.emit.commit()
369
370 if __name__ == "__main__":
371         Conv()