]> www.average.org Git - loctrkd.git/blobdiff - gps303/evstore.py
typechecking: annotate evstore.py
[loctrkd.git] / gps303 / evstore.py
index bb47f3fb21c9c34c178955dbfad7e84e09828dbe..2b23e8e92ef98e4c5ff21a584be786df179859ad 100644 (file)
@@ -1,6 +1,7 @@
 """ sqlite event store """
 
 from sqlite3 import connect, OperationalError
+from typing import Any, List, Tuple
 
 __all__ = "fetch", "initdb", "stow"
 
@@ -16,7 +17,7 @@ SCHEMA = """create table if not exists events (
 )"""
 
 
-def initdb(dbname):
+def initdb(dbname: str) -> None:
     global DB
     DB = connect(dbname)
     try:
@@ -28,7 +29,7 @@ def initdb(dbname):
         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
@@ -53,16 +54,23 @@ def stow(**kwargs):
     DB.commit()
 
 
-def fetch(imei, protos, backlog):
+def fetch(
+    imei: str, matchlist: List[Tuple[bool, int]], 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 = ?
+        f"""select is_incoming, tstamp, packet from events
+                    where ({selector}) and imei = ?
                     order by tstamp desc limit ?""",
-        protos + (imei, backlog),
+        tuple(item for sublist in matchlist for item in sublist)
+        + (imei, backlog),
     )
-    result = [row[0] for row in cur]
+    result = list(cur)
     cur.close()
-    return result
+    return list(reversed(result))