X-Git-Url: http://average.org/gitweb/?a=blobdiff_plain;f=gps303%2Fevstore.py;h=a52a64c1e5ad468676349ad299e6fb14b174eceb;hb=e84104c8d7e93efc4ab2f543e7dfef4cc0208187;hp=c10ecb17e5d7a191d7bf75a76e768138cc9c2755;hpb=96538346bd332d76d2cac5d6a0ef2b4e4a40de30;p=loctrkd.git diff --git a/gps303/evstore.py b/gps303/evstore.py index c10ecb1..a52a64c 100644 --- a/gps303/evstore.py +++ b/gps303/evstore.py @@ -1,6 +1,6 @@ """ sqlite event store """ -from sqlite3 import connect +from sqlite3 import connect, OperationalError __all__ = "fetch", "initdb", "stow" @@ -10,6 +10,7 @@ SCHEMA = """create table if not exists events ( tstamp real not null, imei text, peeraddr text not null, + is_incoming int not null default TRUE, proto int not null, packet blob )""" @@ -18,7 +19,13 @@ SCHEMA = """create table if not exists events ( def initdb(dbname): global DB DB = connect(dbname) - DB.execute(SCHEMA) + try: + DB.execute( + """alter table events add column + is_incoming int not null default TRUE""" + ) + except OperationalError: + DB.execute(SCHEMA) def stow(**kwargs): @@ -26,6 +33,7 @@ def stow(**kwargs): parms = { k: kwargs[k] if k in kwargs else v for k, v in ( + ("is_incoming", True), ("peeraddr", None), ("when", 0.0), ("imei", None), @@ -36,22 +44,30 @@ def stow(**kwargs): assert len(kwargs) <= len(parms) DB.execute( """insert or ignore into events - (tstamp, imei, peeraddr, proto, packet) + (tstamp, imei, peeraddr, proto, packet, is_incoming) values - (:when, :imei, :peeraddr, :proto, :packet) + (:when, :imei, :peeraddr, :proto, :packet, :is_incoming) """, parms, ) DB.commit() -def fetch(imei, protos, backlog): + +def fetch(imei, matchlist, backlog): + # matchlist is a list of tuples (is_incoming, proto) + # returns a list of tuples (is_incoming, timestamp, packet) assert DB is not None - protosel = ", ".join(["?" for _ in range(len(protos))]) + selector = " or ".join( + (f"(is_incoming = ? and proto = ?)" for _ in range(len(matchlist))) + ) cur = DB.cursor() - cur.execute(f"""select packet from events - where proto in ({protosel}) and imei = ? + cur.execute( + f"""select is_incoming, tstamp, packet from events + where ({selector}) and imei = ? order by tstamp desc limit ?""", - protos + (imei, backlog)) - result = [row[0] for row in cur] + tuple(item for sublist in matchlist for item in sublist) + + (imei, backlog), + ) + result = list(cur) cur.close() - return result + return list(reversed(result))