13 def match(self, dummy):
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
27 type = self.types[defaulttype]
30 type = self.types["text"]
33 type = self.types["bool"]
35 c += "\t,`%s` %s\n" % (name, type)
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
44 def execute(self, query, *args):
45 #print query + " %s\n" % str(tuple(args))
46 self.cursor.execute(query, *args);
49 def connect(self, options):
54 args['passwd'] = options.password
56 options.host = 'localhost'
57 args['user'] = options.user
58 args['host'] = options.host
59 args['db'] = options.database
61 self.conn = MySQLdb.connect(**args)
62 self.options = options
63 self.cursor = self.conn.cursor()
65 def __init__(self, options, ctxcols, evcols):
68 self.types["text"] = "varchar(80) default null";
69 self.types["data"] = "double default null";
70 self.types["bool"] = "bool";
72 self.ctxtab = options.prefix + "ctx"
73 self.evtab = options.prefix + "ev"
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)
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`)")
82 keys = "id, " + ", ".join(evcols)
83 marks = ",".join(['%s'] * (len(evcols)+1))
84 self.evinsert = "insert into `%s` values (%s)" % (self.evtab, marks)
86 keys = ", ".join(ctxcols)
87 marks = ",".join(['%s'] * len(ctxcols))
88 self.ctxinsert = "insert into `%s` (%s) values (%s)" % (self.ctxtab, keys, marks)
90 def ev(self, curr_id, evitems):
91 self.execute(self.evinsert, (curr_id,) + tuple(evitems))
93 def ctx(self, ctxitems):
94 self.execute(self.ctxinsert, tuple(ctxitems))
96 id = self.cursor.lastrowid
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)
108 def __init__(self, options, ctxcols, evcols):
111 if options.database == None:
112 print "Have to specify database (file-)name for sqlite"
115 if not options.update:
116 if os.path.isfile(options.database):
117 os.unlink(options.database)
119 self.conn = sqlite3.connect(options.database)
120 self.cursor = self.conn.cursor()
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"
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))
133 keys = "id, " + ", ".join(evcols)
134 marks = ",".join(["?"] * (len(evcols)+1))
135 self.evinsert = "insert into `%s` values (%s)" % (self.evtab, marks)
137 keys = ", ".join(ctxcols)
138 marks = ",".join(["?"] * len(ctxcols))
139 self.ctxinsert = "insert into `%s` (%s) values (%s)" % (self.ctxtab, keys, marks)
143 def ev(self, curr_id, evitems):
144 self.execute(self.evinsert, (curr_id,) + tuple(evitems))
146 def ctx(self, ctxitems):
147 curr_id = self.nextid
149 self.execute(self.ctxinsert, tuple(ctxitems))
151 return self.cursor.lastrowid
157 engines = { 'sqlite3': EmitSqlite3, 'mysql': EmitMysql }
159 # Pass that determines event and context types
160 def find_heads(self):
168 self.valid_keys = set()
174 fields = line.strip().split(";")
176 if (len(fields)-1) % 2 != 0:
177 print "%s: Invalid number of fields after 'P'" % linenr
179 for i in range(1,len(fields),2):
181 if not ctxcols.has_key(key):
182 ctxcols[key] = ctxind
185 elif fields[0] == 'E':
186 if (len(fields)-1) % 2 != 0:
187 print "%s: Invalid number of fields after 'E'" % linenr
190 for i in range(1,len(fields),2):
192 if not self.filter.match(key):
195 if not evcols.has_key(key):
196 self.valid_keys.add(key)
200 self.ctxcols = ctxcols
202 return (ctxcols, evcols)
205 return fileinput.FileInput(files=self.files, openhook=fileinput.hook_compressed)
207 def flush_events(self, id):
209 for e in self.evvals:
216 self.emit.ev(id, self.evvals)
217 self.evvals = [None] * len(self.evvals)
220 if not self.pushpending:
222 self.pushpending = False
223 self.curr_id = self.emit.ctx(self.ctxvals)
225 def fill_tables(self):
233 self.pushpending = False
234 self.ctxvals = [None] * len(self.ctxcols)
235 self.evvals = [None] * len(self.evcols)
237 for line in self.input():
239 items = line.strip().split(';')
242 # Push context command
244 self.flush_events(self.curr_id)
247 for p in range(1,len(items),2):
252 idstack.append(self.curr_id)
254 keyidx = self.ctxcols[key]
255 assert self.ctxvals[keyidx] == None
256 self.ctxvals[keyidx] = val
257 self.pushpending = True
259 # Pop context command
262 # For now... we could optimize this
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)
272 self.curr_id = idstack.pop()
275 print "unmatched pop in line %d, push key %s, pop key: %s" % (lineno, key, popkey)
277 keyidx = self.ctxcols[key]
278 assert self.ctxvals[keyidx] != None
279 self.ctxvals[keyidx] = None
286 # Show that we make progress
288 prec = curr_event * 10 / self.n_events
291 print '%10d / %10d' % (curr_event, self.n_events)
293 for p in range(1,len(items),2):
295 if key not in self.evcols:
298 keyidx = self.evcols[key]
299 if self.evvals[keyidx] != None:
300 self.flush_events(self.curr_id)
303 self.evvals[keyidx] = value
306 parser = optparse.OptionParser('usage: %prog [options] <event file...>', add_help_option=False)
307 parser.add_option("", "--help", help="show this help message and exit", action="help")
308 parser.add_option("", "--update", dest="update", help="update database instead of dropping all existing values", action="store_true", default=False)
309 parser.add_option("-v", "--verbose", dest="verbose", help="verbose messages", action="store_true", default=False)
310 parser.add_option("-f", "--filter", dest="filter", help="regexp to filter event keys", metavar="REGEXP")
311 parser.add_option("-u", "--user", dest="user", help="user", metavar="USER")
312 parser.add_option("-h", "--host", dest="host", help="host", metavar="HOST")
313 parser.add_option("-p", "--password", dest="password", help="password", metavar="PASSWORD")
314 parser.add_option("-D", "--database", dest="database", help="database", metavar="DB")
315 parser.add_option("-e", "--engine", dest="engine", help="engine (sqlite3, mysql)", metavar="ENG", default='sqlite3')
316 parser.add_option("-P", "--prefix", dest="prefix", help="table prefix", metavar="PREFIX", default='')
317 (options, args) = parser.parse_args()
321 self.verbose = options.verbose
331 if not os.path.isfile(file):
332 print "cannot find input file %s" % (file, )
334 self.files.append(file)
336 if len(self.files) < 1:
337 print "no input file to process"
341 self.filter = re.compile(options.filter)
343 self.filter = DummyFilter()
345 if options.engine in self.engines:
346 engine = self.engines[options.engine]
348 print 'engine %s not found' % options.engine
349 print 'we offer: %s' % self.engines.keys()
353 print "determining schema..."
355 (ctxcols, evcols) = self.find_heads()
357 print "context schema:"
359 print "event schema:"
362 self.emit = engine(options, ctxcols, evcols)
365 print "filling tables..."
371 if __name__ == "__main__":