]> www.average.org Git - loctrkd.git/blobdiff - gps303/evstore.py
reimplement backlog query again
[loctrkd.git] / gps303 / evstore.py
index 360ab359505c7a141cdf6a5857d7dbcc14c86b53..a52a64c1e5ad468676349ad299e6fb14b174eceb 100644 (file)
@@ -1,40 +1,73 @@
-from logging import getLogger
-from sqlite3 import connect
+""" sqlite event store """
 
-__all__ = ("initdb", "stow")
+from sqlite3 import connect, OperationalError
 
-log = getLogger("gps303")
+__all__ = "fetch", "initdb", "stow"
 
 DB = None
 
 SCHEMA = """create table if not exists events (
-    timestamp real not null,
+    tstamp real not null,
     imei text,
-    clntaddr text not null,
+    peeraddr text not null,
+    is_incoming int not null default TRUE,
     proto int not null,
-    payload blob
+    packet blob
 )"""
 
 
 def initdb(dbname):
     global DB
-    log.info("Using Sqlite3 database \"%s\"", dbname)
     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(clntaddr, timestamp, imei, proto, payload):
+def stow(**kwargs):
     assert DB is not None
-    parms = dict(
-        zip(
-            ("clntaddr", "timestamp", "imei", "proto", "payload"),
-            (str(clntaddr), timestamp, imei, proto, payload),
+    parms = {
+        k: kwargs[k] if k in kwargs else v
+        for k, v in (
+            ("is_incoming", True),
+            ("peeraddr", None),
+            ("when", 0.0),
+            ("imei", None),
+            ("proto", -1),
+            ("packet", b""),
         )
-    )
+    }
+    assert len(kwargs) <= len(parms)
     DB.execute(
         """insert or ignore into events
-                (timestamp, imei, clntaddr, proto, payload)
-                values (:timestamp, :imei, :clntaddr, :proto, :payload)""",
+                (tstamp, imei, peeraddr, proto, packet, is_incoming)
+                values
+                (:when, :imei, :peeraddr, :proto, :packet, :is_incoming)
+        """,
         parms,
     )
     DB.commit()
+
+
+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
+    selector = " or ".join(
+        (f"(is_incoming = ? and proto = ?)" for _ in range(len(matchlist)))
+    )
+    cur = DB.cursor()
+    cur.execute(
+        f"""select is_incoming, tstamp, packet from events
+                    where ({selector}) and imei = ?
+                    order by tstamp desc limit ?""",
+        tuple(item for sublist in matchlist for item in sublist)
+        + (imei, backlog),
+    )
+    result = list(cur)
+    cur.close()
+    return list(reversed(result))