X-Git-Url: http://average.org/gitweb/?a=blobdiff_plain;f=gps303%2Fevstore.py;h=07b6dc4b760b7de08349611e844168ab0e80470a;hb=bf48ccad4b4b91e7d7e09d1087f5953bc2db97d7;hp=76173624bed9069359f202f46d07e0eba3cc8491;hpb=5e1e7a4d37a1e149d5e899dada7b55a863cd8e64;p=loctrkd.git diff --git a/gps303/evstore.py b/gps303/evstore.py index 7617362..07b6dc4 100644 --- a/gps303/evstore.py +++ b/gps303/evstore.py @@ -1,6 +1,7 @@ """ sqlite event store """ from sqlite3 import connect, OperationalError +from typing import Any, List, Tuple __all__ = "fetch", "initdb", "stow" @@ -11,22 +12,24 @@ SCHEMA = """create table if not exists events ( imei text, peeraddr text not null, is_incoming int not null default TRUE, - proto int not null, + proto text not null, packet blob )""" -def initdb(dbname): +def initdb(dbname: str) -> None: global DB DB = connect(dbname) try: - DB.execute("""alter table events add column - is_incoming int not null default TRUE""") + DB.execute( + """alter table events add column + is_incoming int not null default TRUE""" + ) except OperationalError: DB.execute(SCHEMA) -def stow(**kwargs): +def stow(**kwargs: Any) -> None: assert DB is not None parms = { k: kwargs[k] if k in kwargs else v @@ -35,7 +38,7 @@ def stow(**kwargs): ("peeraddr", None), ("when", 0.0), ("imei", None), - ("proto", -1), + ("proto", "UNKNOWN"), ("packet", b""), ) } @@ -50,14 +53,24 @@ def stow(**kwargs): ) DB.commit() -def fetch(imei, protos, backlog): + +def fetch( + imei: str, matchlist: List[Tuple[bool, str]], backlog: int +) -> List[Tuple[bool, float, bytes]]: + # 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))